SOJ 4033 类数字三角形

Description



Here’s a simple graph problem: Find the shortest path
from the top-middle vertex to the bottom-middle vertex
in a given tri-graph. A tri-graph is an acyclic graph of
(N ≥ 2) rows and exactly 3 columns. Unlike regular
graphs, the costs in a tri-graph are associated with the
vertices rather than the edges. So, considering the example
on the right with N = 4, the cost of going straight
down from the top to bottom along the middle vertices
is 7+13+3+6 = 29. The layout of the directional edges
in the graph are always the same as illustrated in the
figure.

Input

Your program will be tested on one or more test cases.
Each test case is specified using N + 1 lines where the
first line specifies a single integer (2 ≤ N ≤ 100, 000)
denoting the number of rows in the graph. N lines follow,
each specifying three integers representing the cost of the
vertices on the ith row from left to right. The square of
each cost value is less than 1,000,000.
The last case is followed by a line with a single zero.

Output

For each test case, print the following line:
k. n
Where k is the test case number (starting at one,) and n is 
the least cost to go from the top-middle
vertex to the bottom-middle vertex.

Sample Input

4
13 7 5
7 13 6
14 3 12
15 6 16
0

Sample Output



1. 22





一道类似数字三角形的动态规划
#include<iostream>
using namespace std;
int a[100001][4];

int min(int x,int y)
{
    if(x>y)
    return y;
    else
    return x;
}
int main()
{
    int n;
    int k=1;
    while(cin>>n&&n)
    {
        for(int i=1;i<=n;i++)
        for(int j=1;j<=3;j++)
          cin>>a[i][j];
          a[n-1][3]+=a[n][2];
          a[n-1][2]+=min(a[n-1][3],min(a[n][1]+a[n][2],a[n][2]));
          a[n-1][1]+=min(min(a[n][1]+a[n][2],a[n][2]),min(a[n-1][2],a[n][2]));
        for(int i=n-2;i>=1;i--)
        {
            a[i][3]=min(a[i+1][2],a[i+1][3])+a[i][3];
            a[i][2]=min(min(a[i+1][1],a[i+1][2]),min(a[i][3],a[i+1][3]))+a[i][2];
            a[i][1]=min(min(a[i+1][1],a[i][2]),a[i+1][2])+a[i][1];
        }
        cout<<k++<<". "<<a[1][2]<<endl;
    }
    return 0;
}
posted @ 2011-07-19 20:40  Crazy_yiner  阅读(201)  评论(0编辑  收藏  举报