标签:
Tyvj 1221 微子危机——战略
【样例输入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.
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<cstring> 5 #include<vector> 6 #include<queue> 7 #include<algorithm> 8 #define mx 1001 9 10 using namespace std; 11 struct orz 12 { 13 int d,p; 14 friend bool operator <(orz a,orz b) {return a.d>b.d;}//堆和set里面都只有小于号,所以要用小根堆的话要将<重定向为> 15 }; 16 struct Edge{ 17 int to; 18 int w; 19 }; 20 priority_queue < orz > ss; 21 int flag = 0,v[mx],d[mx],n,m,l; 22 vector<Edge> edge[mx]; 23 void input(){ 24 cin>>n>>m>>l; 25 int u,v,wei; 26 Edge test; 27 for(int i = 1;i <= l;i++){ 28 scanf("%d%d%d",&u,&v,&wei); 29 test.to = v; 30 test.w = wei; 31 edge[u].push_back(test); 32 test.to = u; 33 edge[v].push_back(test); 34 } 35 for(int i = 0;i < mx;i++) d[i] = 1000000000; 36 } 37 void dij(int s) 38 { 39 40 d[s]=0; 41 orz tmp; 42 tmp.d=0,tmp.p=s; 43 ss.push(tmp); 44 flag++; 45 int x,dd; 46 Edge j; 47 while (!ss.empty())//不能只做n次,要一直做到堆空 48 { 49 tmp=ss.top(); 50 ss.pop(); 51 x=tmp.p,dd=tmp.d; 52 if (v[x]==flag) continue;//这里一定要判断!!! 53 v[x]=flag; 54 for (int i = 0;i < edge[x].size();i++){ 55 56 j = edge[x][i]; 57 if (d[j.to]>dd+j.w) 58 { 59 d[j.to]=dd+j.w; 60 tmp.d=dd+j.w,tmp.p=j.to; 61 ss.push(tmp); 62 } 63 } 64 65 } 66 } 67 int main(){ 68 input(); 69 dij(m); 70 int ans = 0; 71 for(int i = 1;i <= n;i++){ 72 if(i == m) continue; 73 if(d[i] >= 1000000000){ 74 cout<<"Sth wrong."<<endl; 75 return 0; 76 } 77 ans+=d[i]; 78 } 79 cout<<ans<<" M(s) are needed."<<endl; 80 return 0; 81 }
Tyvj 1176 火焰巨魔的惆怅
5 4
1 2 -3
1 3 -6
3 4 1
4 5 -9
4
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<cstring> 5 #include<algorithm> 6 #include<vector> 7 #include<queue> 8 using namespace std; 9 const int maxn = 100005; 10 const int maxint = ~0U>>1; 11 struct edge{ 12 int v; 13 int w; 14 }; 15 int n,m,vis[maxn],d[maxn]; 16 vector<edge> g[maxn]; 17 void input(){ 18 cin>>n>>m; 19 int u,v,w; 20 edge tmp; 21 for(int i = 1;i <= m;i++){ 22 scanf("%d%d%d",&u,&v,&w); 23 tmp.v = u; 24 tmp.w = w; 25 g[v].push_back(tmp); 26 } 27 for(int i = 1;i <= n;i++){ 28 vis[i] = 0; 29 d[i] = maxint; 30 } 31 } 32 void spfa(){ 33 queue<int> q; 34 q.push(n); 35 d[n] = 1; 36 vis[n] = 1; 37 int now,to,add; 38 while(!q.empty()){ 39 now = q.front(); 40 q.pop(); 41 vis[now] = 0; 42 for(int i = 0;i < g[now].size();i++){ 43 to = g[now][i].v; 44 add = (d[now] - g[now][i].w) >> 1; 45 if((d[now]-g[now][i].w) & 1) add++; 46 if(add <= 0) add = 1; 47 if(d[to] > add){ 48 d[to] = add; 49 if(!vis[to]){ 50 vis[to] = 1; 51 q.push(to); 52 } 53 } 54 } 55 } 56 } 57 int main(){ 58 input(); 59 spfa(); 60 cout<<d[1]; 61 return 0; 62 }
标签:
原文地址:http://www.cnblogs.com/hyfer/p/4835142.html