标签:
2
1
2 512
2
1 2
2 1
YES
512
解题:强连通缩点,看看入度为0 的强连通块中哪个最小选哪个。。。
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 4000; 4 const int INF = 0x3f3f3f3f; 5 struct arc { 6 int to,next; 7 arc(int x = 0,int y = -1) { 8 to = x; 9 next = y; 10 } 11 } e[500000]; 12 int head[maxn],dfn[maxn],low[maxn],belong[maxn]; 13 int minV[maxn],value[maxn],in[maxn],tot,idx,scc,n,m; 14 bool instack[maxn]; 15 stack<int>stk; 16 void init() { 17 for(int i = 0; i < maxn; ++i) { 18 dfn[i] = low[i] = head[i] = -1; 19 instack[i] = false; 20 minV[i] = value[i] = INF; 21 in[i] = belong[i] = 0; 22 } 23 tot = scc = idx = 0; 24 while(!stk.empty()) stk.pop(); 25 } 26 void add(int u,int v) { 27 e[tot] = arc(v,head[u]); 28 head[u] = tot++; 29 } 30 void tarjan(int u) { 31 dfn[u] = low[u] = ++idx; 32 instack[u] = true; 33 stk.push(u); 34 for(int i = head[u]; ~i; i = e[i].next) { 35 if(dfn[e[i].to] == -1) { 36 tarjan(e[i].to); 37 low[u] = min(low[u],low[e[i].to]); 38 } else if(instack[e[i].to]) low[u] = min(low[u],dfn[e[i].to]); 39 } 40 if(low[u] == dfn[u]) { 41 scc++; 42 int v; 43 do { 44 instack[v = stk.top()] = false; 45 stk.pop(); 46 belong[v] = scc; 47 } while(v != u); 48 } 49 } 50 int main() { 51 int u,v,w; 52 while(~scanf("%d",&n)) { 53 init(); 54 scanf("%d",&m); 55 for(int i = 1; i <= m; ++i) { 56 scanf("%d %d",&u,&w); 57 value[u] = w; 58 } 59 scanf("%d",&m); 60 while(m--) { 61 scanf("%d %d",&u,&v); 62 add(u,v); 63 } 64 for(int i = 1; i <= n; ++i) 65 if(dfn[i] == -1) tarjan(i); 66 int ans = 0; 67 for(int i = 1; i <= n; ++i) { 68 minV[belong[i]] = min(minV[belong[i]],value[i]); 69 for(int j = head[i]; ~j; j = e[j].next) { 70 if(belong[i] != belong[e[j].to]) in[belong[e[j].to]]++; 71 minV[belong[e[j].to]] = min(minV[belong[e[j].to]],value[e[j].to]); 72 } 73 } 74 for(int i = 1; i <= scc; ++i) 75 if(!in[i]) { 76 if(minV[i] == INF) { 77 ans = INF; 78 break; 79 } 80 ans += minV[i]; 81 } 82 if(ans < INF) printf("%s\n%d\n","YES",ans); 83 else{ 84 for(int i = 1; i <= n; ++i) 85 if(in[belong[i]] == 0 && minV[belong[i]] == INF && value[i] == INF){ 86 ans = i; 87 break; 88 } 89 printf("%s\n%d\n","NO",ans); 90 } 91 } 92 return 0; 93 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4388108.html