티스토리 뷰
문제 링크 : https://www.acmicpc.net/problem/11049
11049번: 행렬 곱셈 순서
첫째 줄에 입력으로 주어진 행렬을 곱하는데 필요한 곱셈 연산의 최솟값을 출력한다. 정답은 231-1 보다 작거나 같은 자연수이다. 또한, 최악의 순서로 연산해도 연산 횟수가 231-1보다 작거나 같
www.acmicpc.net
결합 순서에 따라 비용이 달라지는 유명(?)한 문제이다.

위의 예를 들여다 보면
dp[a][b] = min(dp[a][b],
dp[a][i] + dp[i+1][b] + (a 행렬의 행) * (i 행렬의 열= i+1 행렬의 행) * (b 행렬의 열) );
을 얻을 수 있다.
전체 코드는 아래와 같다.
#include<bits/stdc++.h>
using namespace std;
vector<int> arr[501];
int dp[501][501];
int recur(int a, int b){
if(a==b) return 0;
int &ret=dp[a][b];
if(ret!=-1) return ret;
ret=INT_MAX;
for(int i=a;i<b;i++)
ret=min(ret,
recur(a,i)+recur(i+1,b)+arr[a][0]*arr[i][1]*arr[b][1]);
return ret;
}
int main(){
memset(dp,-1,sizeof dp);
int n; scanf("%d",&n);
for(int i=1;i<=n;i++){
int a,b; scanf("%d%d",&a,&b);
arr[i].push_back(a), arr[i].push_back(b);
}
printf("%d\n", recur(1,n));
}
dp 초기값을 -1 로 하는 것은 memset 을 이용하는 게 편하기 때문인데,
사실 지금 문제라면 큰 값을 초기값으로 하는 것이 논리적으로는 더 합당할 것이다.
반응형
'DS\Algo > Mathematics' 카테고리의 다른 글
BOJ 10973 이전 순열 (0) | 2022.11.11 |
---|---|
BOJ 2981 GRANICA ( 검문 ) (1) | 2022.10.14 |
BOJ 10826 피보나치 수 4 (0) | 2022.10.02 |
BOJ 10972 다음 순열 (0) | 2022.09.28 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- fenwick tree
- stack
- Vim
- Reference
- Dijkstra
- lazy propagation
- C++ big number
- map
- bash
- 백준
- script
- Shell Programming
- javascript array
- BOJ
- JavaScript
- RUBY
- persistent segment tree
- dynamic programming
- segment tree
- bash script
- Aho-Corasick
- math font
- 다익스트라
- nearest common ancestor
- python3
- 정수론
- shell
- max flow
- number theory
- 세그먼트 트리
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
글 보관함