标签:
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 41873 Accepted Submission(s): 15470
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define N 205 #define M 1005 #define INF 999999999 int city[N][N]; int dist[M]; int n; void Dijkstra(int v0) { int S[N]; for(int i=0; i<n; i++) { dist[i]=city[v0][i]; S[i]=0; } dist[v0]=0; S[v0]=1; for(int i=1; i<n; i++) { int mindist=INF; int flag=v0; for(int j=0; j<n; j++) if((!S[j])&&dist[j]<mindist) { flag=j; mindist=dist[j]; } S[flag]=1; for(int j=0; j<n; j++) if((!S[j])&&city[flag][j]<INF) { if(dist[j]>dist[flag]+city[flag][j]) dist[j]=dist[flag]+city[flag][j]; } } } int main() { int m,a,b,x; while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0; i<n; i++) for(int j=0; j<n; j++) { if(i==j) city[i][j]=0; else city[i][j]=INF; } for(int i=0; i<m; i++) { scanf("%d%d%d",&a,&b,&x); if(x<city[a][b]) { city[a][b]=x; city[b][a]=x; } } scanf("%d%d",&a,&b); Dijkstra(a); if(dist[b]==INF) printf("-1\n"); else printf("%d\n",dist[b]); } return 0; }
floyd:
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define N 205 #define M 1005 #define INF 999999999 int city[N][N]; int n; void floyd() { for(int k=0; k<n; k++) for(int i=0; i<n; i++) for(int j=0; j<n; j++) { if(city[i][j]>city[i][k]+city[k][j]) city[i][j]=city[i][k]+city[k][j]; } } int main() { int m,a,b,x; while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0; i<n; i++) for(int j=0; j<n; j++) { if(i==j) city[i][j]=0; else city[i][j]=INF; } for(int i=0; i<m; i++) { scanf("%d%d%d",&a,&b,&x); if(x<city[a][b]) { city[a][b]=x; city[b][a]=x; } } scanf("%d%d",&a,&b); floyd(); if(city[a][b]==INF) printf("-1\n"); else printf("%d\n",city[a][b]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/jasonlixuetao/p/5409308.html