Keep on counting minimum possible cost for each position. Use previous value to avoid calculating same thing again and again.
#include<stdio.h> #define MIN(a,b) a<b? a:b #define inf 99999999 int main() { int fc,cost[22][5],a[22][5],i,j,n,t,kase,x,y; scanf("%d",&t); kase=0; while (kase++<t) { scanf("%d",&n); for (i=1;i<=n;i++) for (j=1;j<=3;j++) scanf("%d",&a[i][j]); cost[1][1]=a[1][1]; cost[1][2]=a[1][2]; cost[1][3]=a[1][3]; for (i=2;i<=n;i++) { cost[i][1]=cost[i-1][2]+a[i][1]; cost[i][1]=MIN(cost[i][1],cost[i-1][3]+a[i][1]); cost[i][2]=cost[i-1][1]+a[i][2]; cost[i][2]=MIN(cost[i][2],cost[i-1][3]+a[i][2]); cost[i][3]=cost[i-1][2]+a[i][3]; cost[i][3]=MIN(cost[i][3],cost[i-1][1]+a[i][3]); } fc=inf; for (i=1;i<=3;i++) fc=MIN(fc,cost[n][i]); printf("Case %d: %d\n",kase,fc); } return 0; }
No comments:
Post a Comment