标签:
3 1 0 1 1 4 4 0 1 10 0 2 10 1 3 20 2 3 30
impossible 40 0
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int INF = 0x3f3f3f3f; 4 const int maxn = 1010; 5 struct arc { 6 int u,v,w; 7 } e[50000]; 8 int in[maxn],pre[maxn],hs[maxn],vis[maxn],Rt; 9 int DMST(int root,int n,int m,int ret = 0) { 10 while(true) { 11 for(int i = 0; i < n; ++i) { 12 hs[i] = vis[i] = -1; 13 in[i] = INF; 14 } 15 for(int i = 0; i < m; ++i) { 16 if(e[i].u != e[i].v && e[i].w < in[e[i].v]) { 17 in[e[i].v] = e[i].w; 18 pre[e[i].v] = e[i].u; 19 if(e[i].u == root) Rt = i; 20 } 21 } 22 for(int i = 0; i < n; ++i) 23 if(root != i && in[i] == INF) return -1; 24 int cnt = in[root] = 0; 25 for(int i = 0; i < n; ++i) { 26 ret += in[i]; 27 int v = i; 28 while(vis[v] != i && hs[v] == -1 && v != root) { 29 vis[v] = i; 30 v = pre[v]; 31 } 32 if(v != root && hs[v] == -1) { 33 for(int u = pre[v]; u != v; u = pre[u]) hs[u] = cnt; 34 hs[v] = cnt++; 35 } 36 } 37 if(!cnt) break; 38 for(int i = 0; i < n; ++i) 39 if(hs[i] == -1) hs[i] = cnt++; 40 for(int i = 0; i < m; ++i) { 41 int u = e[i].u; 42 int v = e[i].v; 43 e[i].u = hs[u]; 44 e[i].v = hs[v]; 45 if(e[i].u != e[i].v) e[i].w -= in[v]; 46 } 47 n = cnt; 48 root = hs[root]; 49 } 50 return ret; 51 } 52 int main() { 53 int n,m,sum; 54 while(~scanf("%d%d",&n,&m)) { 55 for(int i = sum = 0; i < m; ++i) { 56 scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w); 57 sum += e[i].w; 58 } 59 sum++; 60 for(int i = 0; i < n; ++i) { 61 e[i + m].u = n; 62 e[i + m].v = i; 63 e[i + m].w = sum; 64 } 65 int ret = DMST(n,n + 1,n + m); 66 if(ret == -1 || ret > (sum<<1)) puts("impossible"); 67 else printf("%d %d\n",ret-sum,Rt - m); 68 puts(""); 69 } 70 return 0; 71 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4761665.html