poj 2387 Til the Cows Come Home

/* Name:poj 2387 Til the Cows Come Home Author: Unimen Date: 25/04/11 19:21 Description:单源最短路径Dijkistra, SPFA解法 */ /* 解题报告: 1、注意有重边(即到某一点的权值有多种), 在输入时处理掉 */ //Dijkistra解法 #include <iostream> using namespace std; const int MAXN = 1200; const int oo = 2100000000; int t, n; int g[MAXN][MAXN]; int dis[MAXN], visited[MAXN]; void Dijkistra() { int i, j; for(i=1; i<=n; ++i) { dis[i] = g[1][i]; visited[i] = 0; } dis[1] = 0, visited[1] = 1; for(i=1; i<n; ++i) { int nMin = oo; int index = 0; for(j=1; j<=n; ++j) { if(!visited[j] && dis[j]<nMin) { index = j; nMin = dis[j]; } } visited[index] = 1; for(j=1; j<=n; ++j) { if(!visited[j] && g[index][j]!=oo && dis[j]>dis[index]+g[index][j]) dis[j]=dis[index]+g[index][j]; } } } int main() { int i, j; while(cin>>t>>n) { for(i=1; i<=n; ++i) for(j=1; j<=n; ++j) g[i][j] = oo; for(i=1; i<=t; ++i) { int a, b, w; cin>>a>>b>>w; if(w < g[a][b]) g[a][b] = g[b][a] = w; } Dijkistra(); cout<<dis[n]<<endl; } return 0; } //SPFAQ解法 #include <iostream> #include <queue> #include <cstring> using namespace std; const int MAXN = 1200; const int oo = 21000000; int t, n; int g[MAXN][MAXN]; int dis[MAXN]; void spfa() { queue<int> que; que.push(1); dis[1] = 0; while(!que.empty()) { int x = que.front(); que.pop(); for(int i=1; i<=n; i++) { if(g[x][i]!=oo && dis[i] > dis[x] + g[x][i]) { dis[i] = dis[x] + g[x][i]; que.push(i); } } } } int main() { int i, j; while(cin>>t>>n) { for(i=1; i<=n; ++i) { for(j=1; j<=n; ++j) { g[i][j] = oo; } } for(i=1; i<=t; ++i) { int a, b, w; cin>>a>>b>>w; if(g[a][b] > w) g[a][b] = g[b][a] =w; } for(i=1; i<=n; ++i) dis[i] = oo; spfa(); cout<<dis[n]<<endl; } return 0; }

你可能感兴趣的:(Date,OO)