poj 3767 I Wanna Go Home
题目分析: 这个题属于典型的dijkstra 算法的题; n个村庄,m 条路 和两村庄之间所用时间 |
#include<stdio.h> #define max 0x7fffffff int grah[601][601]; int root[601]; int n; void dij() { int d[601]; bool vis[601]={false}; int i,j,pos=0; for(i = 0;i < n; i++) d[i] = grah[0][i]; vis[0] = true ; for( i= 1; i <= n; i++) { int min=max; for(j = 0; j < n; j++) { if( ! vis[j] && min > d[j]) { min=d[j]; pos = j; } } vis[pos] = true; for( j = 0;j < n ;j++) { if( !vis[j] && grah[pos][j] < max && !(root[pos] == 2 && root[j] == 1)) { if(d[j] > d[pos]+ grah[pos][j]) d[j] = d[pos] + grah[pos][j]; } } } if(d[1] < max) printf("%d\n",d[1]); else printf("-1\n"); } int main() { // freopen("e://1.txt","r",stdin); int m,x,y,z,i,j; while(scanf("%d",&n),n) { for(i = 0;i < n;i++) for(j = 0;j < n;j++) { if(i==j) grah[i][j]=0; else grah[i][j]=max; } scanf("%d",&m); while(m--) { scanf("%d%d%d",&x,&y,&z); grah[x-1][y-1]=grah[y-1][x-1]=z; } for(i = 0;i < n;i++) scanf("%d",root+i); dij(); } return 0; }
Just a little, maybe change the world