Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
我用Dijkstra算法。自己做了好几个例子都对着,什么地方可能有错误?第一次的最短路经记录有问题? 代码如下: #include <iostream> //3068C using namespace std; //³ÌÐò¶ÔÁË µ«ÊÇËã·¨µÄЧÂÊÌ«µÍ£¬³ÌÐòÕûÌå½á¹¹¿´ÆðÀ´Ò²ºÜ²»ºÃ struct Edge { _int64 i,j,c; bool used; }; Edge ed[10000]; #define MAX 999999999 _int64 e,M,N; _int64 cost[65][65]; _int64 use[65][65]; //µÚÒ»´ÎÑ¡Ôñ×îÓÅÊÆʱi,jÔÚMÖÐËùÓÃµÄ _int64 dp[65];//, num_dp; bool final[65]; _int64 L[65], rst; void load1() //ÓÉÓÚÿÖÖ·½·¨Ö»ÄÜÓÃÒ»´Î£¬ËùÒÔ´æÔÚÏûºÄ£¬ÐèÒªÁ½´Î¼Ç¼ { for(_int64 i=0;i<N;i++){ for(_int64 j=0;j<N;j++){ use[i][j] = -1; } } for(i=0;i<M;i++){ if( ed[i].c<cost[ed[i].i][ed[i].j]){ cost[ed[i].i][ed[i].j] = ed[i].c; use[ed[i].i][ed[i].j] = i; } } for(i=0;i<N-1;i++){ if( cost[0][0] < MAX ) L[i] = 0; else L[i] = -1; } } void load2() { for(_int64 i=0;i<M;i++) if(!ed[i].used && ed[i].c<cost[ed[i].i][ed[i].j]) cost[ed[i].i][ed[i].j] = ed[i].c; } void Diskstra() { _int64 i,j,p,min ; for(i=0;i<N;i++){ final[i] = false; dp[i] = cost[0][i]; } final[0] = true; for(i=1; i<N;i++){ //Ö÷Ñ­»· min = MAX; p=-1; for( j= 0 ; j<N;j++) { //Ñ°ÕҴζÌ·¾¶, ÓÐÕÒ²»µ½µÄ¿ÉÄÜÐÔÄØ if(!final[j] ) if( dp[j] < min) {p = j; min = dp[j];} } if(p==-1) //ûÕÒµ½£¬·µ»Ø×î¶Ì·¾¶ { rst = MAX; return; } final[p] = true; if(p == N-1) break; for(j=0; j<N;j++) //¸úРif( !final[j] && (min+cost[p][j] < dp[j] ) ) { dp[j] = min+cost[p][j] ; L[j] = p; //¼Ç¼ÄÄÒ»¸ö¶¨µãË¢ÐÂÁË×Ô¼ºµÄ·¾¶³¤¶È } } rst +=dp[N-1]; } void work(_int64 th) { rst =0; printf("Instance #%I64d: ",th); _int64 i,j; for(i=0;i<M;i++) //±ØÐë ed[i].used = false; for(i=0;i<N;i++){ //±ØÐë for(j=0;j<N;j++) cost[i][j] =MAX; cost[i][i] = 0; } load1(); Diskstra(); if(rst >=MAX) {printf("Not possible\n"); return;} i = N-1; while(true){ ed[ use[L[i]][i] ].used =true; i = L[i]; if(i==0) break; } for(i=0;i<N;i++){ //±ØÐë for(j=0;j<N;j++) cost[i][j] =MAX; cost[i][i] = 0; } load2(); Diskstra(); if(rst >=MAX) {printf("Not possible\n"); return;} printf("%I64d\n",rst); } _int64 main() { scanf("%d%d",&N,&M); _int64 p; _int64 th=1; while(N!=0 && M!=0){ p=0; while(p<M){ scanf("%d%d%d",&ed[p].i,&ed[p].j,&ed[p].c); p++; } work(th); th++; scanf("%d%d",&N,&M); } return 0; } Followed by:
Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator