依旧是一道简单的DFS求最短路径的联系。PAT1018也是用这种思路去写的,但是不知道为什么至今未A。。。最近在考虑什么时候去考PAT,好像该给自己一点压力,原本的计划是去考明年三月的那次,但是现在的进度貌似太慢了,在考虑要不要去试试十二月的这次。。。。
#include<stdio.h>
#include<string.h>
#define MAX 999
struct node{
int mDis,mCost,mPath[505];
}s1,s2;
int minDis,minCost,n,m,s,d,map[505][505],num[505][505],visit[505],start,end,dis,cost,count = 0;
void dfs(int c){
if(c == d){
if(s1.mDis < minDis || (s1.mDis == minDis && s1.mCost < minCost)){
minDis = s1.mDis;
minCost = s1.mCost;
s2 = s1;
}
return ;
}
for(int i = 0;i<n;i++){
if(map[c][i] != -1 && visit[i] == 0){
visit[i] = 1;
int tempDis = s1.mDis;
int tempCost = s1.mCost;
s1.mDis += map[c][i];
s1.mCost += num[c][i];
count++;
s1.mPath[count] = i;
dfs(i);
count--;
s1.mDis = tempDis;
s1.mCost = tempCost;
visit[i] = 0;
}
}
}
int main(){
scanf("%d %d %d %d",&n,&m,&s,&d);
memset(map,-1,sizeof(map));
memset(num,-1,sizeof(num));
memset(visit,0,sizeof(visit));
for(int i = 0;i<m;i++){
scanf("%d %d %d %d",&start,&end,&dis,&cost);
map[start][end] = map[end][start] = dis;
num[start][end] = num[end][start] = cost;
}
minDis = minCost = MAX;
dfs(s);
printf("%d",s);
for(int i = 1;s2.mPath[i] != d;i++){
printf(" %d",s2.mPath[i]);
}
printf(" %d %d %d\n",d,minDis,minCost);
return 0;
}