ural 1210. Kind Spirits

给出图,每一层有好几个点,求从0层到最高层的最短路。

 

开始没多想,直接拿最短路写的,建图稍显麻烦,不过还好啦。1A了。后来想起来党姐说DP可以做,想了想,这不就类似数字三角形嘛,用DP也过了,DP真短。

 

最短路SPFA

 

#include <queue> #include <stack> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <limits.h> #include <string.h> #include <algorithm> using namespace std; const int MAX = 1000; int lev; int l[MAX],map[MAX][MAX]; int n; typedef struct NODE{ int d,to;}NODE; int dis[MAX]; queue<NODE> q; int SPFA(int s) { bool inq[MAX]; memset( inq,false,sizeof(inq)); for(int i=0; i<=n; i++) dis[i] = INT_MAX; NODE tmp; tmp.d = 0; tmp.to = s; dis[s] = 0; inq[s] = true; q.push(tmp); while( !q.empty() ) { NODE tmp = q.front(); q.pop(); inq[tmp.to] = false; int now = tmp.to,len = tmp.d; for(int i=0; i<=n; i++) if( map[now][i] != INT_MAX && dis[i] > dis[now] + map[now][i] ) { dis[i] = dis[now] + map[now][i]; if( !inq[i] ) { inq[i] = true; NODE tmp; tmp.to = i; tmp.d = dis[i]; q.push(tmp); } } } int mmin = INT_MAX; for(int i=n-l[lev]+1; i<=n; i++) if( dis[i] < mmin ) mmin = dis[i]; return mmin; } int main() { int ind,cost,sum; char str[5]; scanf("%d",&lev); memset(l,0,sizeof(l)); for(int i=0; i<MAX; i++) for(int k=0; k<MAX; k++) map[i][k] = INT_MAX; l[0] = 1; sum = 0; for(int i=1; i<=lev; i++) { scanf("%d",&l[i]); for(int k=1; k<=l[i]; k++) while( scanf("%d",&ind) && ind ) { scanf("%d",&cost); map[sum-l[i-1]+ind][sum+k] = cost; } sum += l[i]; if( i != lev ) scanf("%s",str); } n = sum; int ans = SPFA(0); printf("%d/n",ans); return 0; }  

 

 

 

DP

 

#include <queue> #include <stack> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <limits.h> #include <string.h> #include <algorithm> using namespace std; const int MAX = 35; int dp[MAX]; int dpp[MAX]; int lev; int main() { int ind,cost,l; char str[5]; scanf("%d",&lev); dpp[1] = 0; for(int i=1; i<=lev; i++) { for(int k=0; k<MAX; k++) dp[k] = INT_MAX; scanf("%d",&l); for(int k=1; k<=l; k++) while( scanf("%d",&ind) && ind ) { scanf("%d",&cost); if( dp[k] > dpp[ind] + cost ) dp[k] = dpp[ind] + cost; } if( i != lev ) scanf("%s",str); memcpy(dpp,dp,sizeof(dp)); } int mmin = INT_MAX; for(int i=1; i<=l; i++) if( dpp[i] < mmin ) mmin = dpp[i]; printf("%d/n",mmin); return 0; }  

你可能感兴趣的:(struct)