【Pat 1003】Emergency
一、前言
题目就是求单源点最短路径的变种,没有AC以后,一个WA,以后有时间回过头来看看。要注意的是
- 求输出最短路径种类和最短路径下的最大权重
-
外层遍历的初始值为1,因为start节点去掉,应该少遍历一个单
for (i=1;i<num;i++) { cur=getCur(path,num); flag[cur]=0; if(cur==end) break; for (j=0;j<num;j++) { if(flag[j]){ tmp=path[cur]+map[cur][j]; if(tmp<=path[j]){ path[j]=tmp; tmp_hand=countteam[cur]+team[j]; countteam[j]=tmp_hand>countteam[j]?tmp_hand:countteam[j]; countroad[j]+=countroad[cur]; } } } }
- 最短路径种类的求取
- 最大权重的求取
2.3解决方法其实都是明白:设某条路径为start->...->n->k->end;
则路径种类:countRoad(k)+=countRoad();
最大权重:countWeight(k),countWeight(n)+Weight(k)的最大值
二、代码
View Code
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 1000 int team[500]; int map[500][500]; int flag[500]; int getCur(int path[],int len) { int i,tmp=MAX,index; for (i=0;i<len;i++) if(flag[i]&&path[i]<=tmp) {index=i;tmp=path[i];} return index; } int getMinPath(int path[],int countteam[],int start,int end,int num,int countroad[]) { int i,j,cur,tmp,tmp_hand; flag[start]=0; for (i=0;i<num;i++) if(i!=start) { path[i]=map[start][i]; if(path[i]!=MAX) {countroad[i]=1;countteam[i]+=countteam[start];} } for (i=1;i<num;i++) { cur=getCur(path,num); flag[cur]=0; if(cur==end) break; for (j=0;j<num;j++) { if(flag[j]){ tmp=path[cur]+map[cur][j]; if(tmp<=path[j]){ //若新的最短路径出现 path[j]=tmp; tmp_hand=countteam[cur]+team[j];//计算这条路劲带来的权重 countteam[j]=tmp_hand>countteam[j]?tmp_hand:countteam[j];//权重改为最大权重 countroad[j]+=countroad[cur];//最短路径种类添加上新路径带来的种类 } } } } return 0; } int main() { int n,m,start,end; int i,x,y,z; int *countteam; int *road; int *countroad; while(scanf("%d%d%d%d",&n,&m,&start,&end)!=EOF) { for (i=0;i<n;i++) { scanf("%d",&team[i]);flag[i]=1; for (x=0;x<n;x++) map[i][x]=MAX; } for (i=0;i<m;i++) { scanf("%d%d%d",&x,&y,&z); map[x][y]=z; map[y][x]=z; } countteam=(int *)malloc(n*sizeof(int)); if(countteam==NULL) return 1; for (i=0;i<n;i++) countteam[i]=team[i]; countroad=(int *)malloc(n*sizeof(int)); if(countroad==NULL) return 1; memset(countroad,0,n*sizeof(int)); road=(int *)malloc(n*sizeof(int)); if(road==NULL) return 1; memset(road,0,n*sizeof(int)); getMinPath(road,countteam,start,end,n,countroad); printf("%d %d\n",countroad[end],countteam[end]); } return 0; }