标签:
【样例输入1】
5 3 6
1 2 1
1 3 3
2 3 1
4 1 5
4 5 2
5 1 2
【样例输入2】
5 3 4
1 2 1
1 3 3
2 3 1
5 1 2
【样例输出1】
13 M(s) are needed.
【样例输出2】
Sth wrong.
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<queue> #include<algorithm> #define mx 1001 using namespace std; struct orz { int d,p; friend bool operator <(orz a,orz b) {return a.d>b.d;}//堆和set里面都只有小于号,所以要用小根堆的话要将<重定向为> }; struct Edge{ int to; int w; }; priority_queue < orz > ss; int flag = 0,v[mx],d[mx],n,m,l; vector<Edge> edge[mx]; void input(){ cin>>n>>m>>l; int u,v,wei; Edge test; for(int i = 1;i <= l;i++){ scanf("%d%d%d",&u,&v,&wei); test.to = v; test.w = wei; edge[u].push_back(test); test.to = u; edge[v].push_back(test); } for(int i = 0;i < mx;i++) d[i] = 1000000000; } void dij(int s) { d[s]=0; orz tmp; tmp.d=0,tmp.p=s; ss.push(tmp); flag++; int x,dd; Edge j; while (!ss.empty())//不能只做n次,要一直做到堆空 { tmp=ss.top(); ss.pop(); x=tmp.p,dd=tmp.d; if (v[x]==flag) continue;//这里一定要判断!!! v[x]=flag; for (int i = 0;i < edge[x].size();i++){ j = edge[x][i]; if (d[j.to]>dd+j.w) { d[j.to]=dd+j.w; tmp.d=dd+j.w,tmp.p=j.to; ss.push(tmp); } } } } int main(){ input(); dij(m); int ans = 0; for(int i = 1;i <= n;i++){ if(i == m) continue; if(d[i] >= 1000000000){ cout<<"Sth wrong."<<endl; return 0; } ans+=d[i]; } cout<<ans<<" M(s) are needed."<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/hyfer/p/5811786.html