http://acm.hdu.edu.cn/showproblem.php?pid=3790
题意 : 经典的求最短路问题。表示上午刚刚学了点并查集后,因为有场最短路的练习,就突击学习了下最短路,表示很伤的学了刘汝佳的算法竞赛书上的代码,再加上肉鸽学长的教导,终于写出了我的ACM生涯中的第一个最短路(orz...)
典型的Dijkstra算法,用dis和cos两个数组分别保存距离和花费...
//Danceonly #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int INF = 100000007; const int maxn = 1005; #define MIN(a,b) (a > b ? b : a) #define MAX(a,b) (a > b ? a : b) struct node { int d,p; }q[maxn][maxn]; int vis[maxn],dis[maxn],cos[maxn]; int N,M; int main() { while (scanf("%d%d",&N,&M) == 2 && (N || M)) { for (int i=1;i<=N;i++) for (int j=1;j<=N;j++) q[i][j].d = q[i][j].p = INF; for (int i=1;i<=M;i++) { int a,b,d,p; scanf("%d%d%d%d",&a,&b,&d,&p); if (q[a][b].d > d || (q[a][b].d == d && q[a][b].p > p)) { q[a][b].d = d; q[a][b].p = p; } q[b][a] = q[a][b]; } int startx,endx; scanf("%d%d",&startx,&endx); memset(vis,0,sizeof(vis)); //vis[startx] = 1; for (int i=1;i<=N;i++) { dis[i] = (i == startx ? 0 : INF); cos[i] = dis[i]; } for (int i=1;i<=N;i++) { int x,m = INF,n = INF; for (int y=1;y<=N;y++) if (vis[y] == 0) if (dis[y] < m || (dis[y] == m && cos[y] < n)) { x = y; m = dis[x]; n = cos[x]; } vis[x] = 1; for (int y=1;y<=N;y++) { if (dis[y] > dis[x] + q[x][y].d){dis[y] = dis[x] + q[x][y].d;cos[y] = cos[x] + q[x][y].p;} else if (dis[y] == dis[x] + q[x][y].d && cos[y] > cos[x] + q[x][y].p) { dis[y] = dis[x] + q[x][y].d; cos[y] = cos[x] + q[x][y].p; } else ; } } printf("%d %d\n",dis[endx],cos[endx]); } return 0; } /* 3 3 1 2 5 6 2 3 4 5 1 3 4 5 1 3 */