기본 콘텐츠로 건너뛰기

[BOJ 4883] 삼각 그래프 - DP, vector 이차원배열 초기화

1번째 행부터 시작해서 column을 순차적으로 돌면서 dp값을 갱신한다.


#include<cstdio>
#include<vector>
#define MAX 10000000
using namespace std;
int offset[3][4][2] = { { {-1,0}, {-1, 1} }, { {0,-1},{-1,-1},{-1,0},{-1,1} }, { {0,-1},{-1,-1}, {-1,0} } };
int move_len[] = {2,4,3};
int min(int a,int b){
if (a<b) return a;
else return b;
}
int main(void)
{
int N;
int loop = 0;
scanf("%d",&N);
while (N != 0){
vector<vector<int>> arr(N,vector<int>(3,0));
for (int i=0;i<N;i++){
for (int j=0; j<3; j++)
scanf("%d",&arr[i][j]);
}
vector<vector<int>> dp(N,vector<int>(3,0));
dp[0][1] = arr[0][1];
dp[0][2] = arr[0][1]+arr[0][2];
for (int i=1;i<N;i++){
for (int j=0; j<3; j++)
{
dp[i][j] = MAX;
for (int k=0;k<move_len[j];k++){
int x_cor = i+offset[j][k][0];
int y_cor = j+offset[j][k][1];
if (x_cor == 0 && y_cor == 0)
continue;
dp[i][j] = min(dp[x_cor][y_cor] + arr[i][j],dp[i][j]);
}
}
}
printf("%d. %d\n",++loop,dp[N-1][1]);
scanf("%d",&N);
}
}
view raw [BOJ 4883] hosted with ❤ by GitHub

댓글

이 블로그의 인기 게시물

Tree traversal의 3가지

1. 전위 순회 (Preorder Traversal) Root -> Left Tree -> Right Tree   ( 루트를 제일 처음에 방문 ) 2. 중위 순회 (Inorder Traversal) Left Tree -> Root -> Right Tree   ( 루트를 중간에 방문 ) 3. 후위 순회 (Postorder Traversal) Left Tree -> Right Tree -> Root   ( 루트를 제일 마지막에 방문 ) <소스코드> 출처 : http://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder /// C program for different tree traversals #include <stdio.h> #include <stdlib.h> /* A binary tree node has data, pointer to left child    and a pointer to right child */ struct node {      int data;      struct node* left;      struct node* right; }; /* Helper function that allocates a new node with the    given data and NULL left and right pointers. */ struct node* newNode(int data) {      struct node* node = (struct node*)                 ...