poj3767 I Wanna Go Home

 1 #include<stdio.h>

 2 #include<string.h>

 3 #include<stdlib.h>

 4 #define Max 0xfffffff

 5 int m[610][610],p[610];

 6 bool vis[610];

 7 bool leader[610];

 8 int vexnum,arcnum;

 9 void dijkstra()

10 {

11     int i,j,k,t,min;

12     memset(vis,0,sizeof(vis));

13     for(i=1;i<=vexnum;++i)

14         p[i]=m[1][i];

15     for(vis[1]=k=1;k<vexnum;++k){

16         for(min=Max,i=1;i<=vexnum;++i)

17             if(!vis[i]&&min>p[i]){

18                 min=p[i];

19                 t=i;

20             }

21             vis[t]=1;

22             for(i=1;i<=vexnum;++i)

23                 if(!vis[i]&&p[i]>min+m[t][i])

24                     p[i]=min+m[t][i];

25     }

26 }

27 int main()

28 {

29     int i,j,t,a,b,w;

30     while(scanf("%d",&vexnum),vexnum&&scanf("%d",&arcnum)){

31         for(i=1;i<=vexnum;++i)

32             for(j=1;j<=vexnum;++j)

33                 m[i][j]=m[j][i]=Max;

34         for(i=0;i<arcnum;++i){

35             scanf("%d%d%d",&a,&b,&w);

36             if(w<m[a][b])

37                 m[a][b]=m[b][a]=w;

38         }

39         for(i=1;i<=vexnum;++i){

40             scanf("%d",&t);

41             leader[i]=t-1;

42         }

43         for(i=1;i<=vexnum;++i)

44             for(j=1;j<=vexnum;++j){

45                 if(leader[i]!=leader[j]){

46                     if(leader[i]) m[i][j]=Max;

47                     else m[j][i]=Max;

48                 }

49             }

50         dijkstra();

51         if(p[2]<Max) printf("%d\n",p[2]);

52         else printf("-1\n");//忘加了一个“-1”,贡献了一个WA

53     }

54     system("pause");

55     return 0;

56 }

//稍微变化一下的dijktra

你可能感兴趣的:(home)