题目链接:https://vjudge.net/problem/HDU-2544
题目:
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0Sample Output
3 2
思路:模板题,个人喜欢spfa算法,优先队列操作,代码如下:
#include<iostream> #include<queue> #include<cstring> #include<cstdio> #define MAX 0x3f3f3f3f using namespace std; //const int maxn=2e5+7; typedef long long ll; const int maxn=105; bool book[maxn]; int mon[maxn][maxn]; int d[maxn]; int mudi,T; void spfa(int a) { memset(book,false,sizeof(book));
memset(d,MAX,sizeof(d)); d[a]=0; queue<int>qu; qu.push(a); book[a]=true; int now; while(!qu.empty()) { now=qu.front(); qu.pop(); book[now]=false; for(int i=1;i<=mudi;i++) { if(d[i]>d[now]+mon[now][i]) { d[i] = d[now] + mon[now][i]; if (book[i] == 0) { qu.push(i); book[i] = true; } } } } } int main() { while(scanf("%d%d",&mudi,&T)) { if(mudi==0&&T==0) break; for(int i=1;i<=mudi;++i) { for(int j=1;j<=i;++j) { if(i==j) mon[i][j]=0; else mon[i][j]=mon[j][i]=MAX; } } int x,y,z; for(int i=1;i<=T;i++) { cin>>x>>y>>z; mon[x][y]=mon[y][x]=z; } spfa(1); printf("%d\n",d[mudi]); } return 0; }
原文:https://www.cnblogs.com/Vampire6/p/11198464.html