题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1874
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15743 Accepted Submission(s): 5384
3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
//注意对两顶点时间可能有多条路的解决
flody代码:
#include<iostream> #include<string> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<cmath> #include<vector> using namespace std; #define inf 10000000 int map[201][201]; int N,i,j,k,A,B,C,M; void Floyd(){ for(k=0;k<N;k++) for(i=0;i<N;i++) for(j=0;j<N;j++) if(map[i][j]>map[i][k]+map[k][j]) map[i][j]=map[i][k]+map[k][j]; } void init(){ for(i=0;i<N;i++) for(j=0;j<N;j++){ map[i][j]=inf; if(i==j) map[i][j]=0; } } int main(){ while(cin>>N>>M){ init(); while(M--){ cin>>A>>B>>C; if(C<map[A][B]) map[A][B]=map[B][A]=C; } cin>>A>>B; Floyd(); if(map[A][B]<inf) cout<<map[A][B]<<endl; else cout<<-1<<endl; } return 0; }
spfa代码:
#include<cstdio> #include<iostream> #include<queue> #include<cmath> #include<cstring> #include<string> #include<algorithm> #include<stack> using namespace std; typedef long long LL; #define clr(x) memset(x,0,sizeof(x)); #define sf scanf #define pf printf #define INF 1<<29 const int maxn=305; int map[maxn][maxn]; int dis[maxn]; bool vis[maxn]; int n,m,t; int spfa(int s,int t){ queue<int>Q; while(!Q.empty()) Q.pop(); memset(vis,false,sizeof(vis)); for(int i=0;i<n;i++) dis[i]=INF; dis[s]=0; vis[s]=true; Q.push(s); while(!Q.empty()){ int now=Q.front(); Q.pop(); vis[now]=false; for(int i=0;i<n;i++) if(dis[now]+map[i][now]<dis[i]){ dis[i]=dis[now]+map[i][now]; if(!vis[i]){ vis[i]=true; Q.push(i); } } } return dis[t]; } void init(){ for(int i=0;i<n;i++) for(int j=0;j<n;j++){ if(i==j) map[i][j]=0; else map[i][j]=INF; } } int main(){ int a,b,c; while(sf("%d%d",&n,&m)!=EOF){ init(); for(int i=0;i<m;i++){ sf("%d%d%d",&a,&b,&c); map[a][b]=map[b][a]=min(map[a][b],c); } sf("%d%d",&a,&b); if(spfa(a,b)<INF) pf("%d\n",spfa(a,b)); else pf("-1\n"); } return 0; }