标签:
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 0 Accepted Submission(s): 0
#include<bits/stdc++.h> using namespace std; const int maxn = 1e4+5,maxm = 2e5+10; int n,m; int val[maxn]; int head[maxn],nxt[maxm],to[maxm]; int deg[maxn],ecnt; bool rmvd[maxn]; void addEdge(int u,int v) { to[ecnt] = v; nxt[ecnt] = head[u]; head[u] = ecnt++; deg[u]++; } void topo() { queue<int> q; for(int i = 1; i <= n; i++){ if(deg[i] <= 1){ rmvd[i] = true; q.push(i); } } while(q.size()){ int u = q.front(); q.pop(); for(int i = head[u]; ~i; i = nxt[i]){ int v = to[i]; if(!rmvd[v] && --deg[v] == 1){ q.push(v); rmvd[v] = true; } } } } long long sum[maxn]; int pa[maxn],cnt[maxn]; int fdst(int x) { return x==pa[x]?x:pa[x]=fdst(pa[x]); } int main() { //freopen("in.txt","r",stdin); int T; scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); for(int i = 1; i <= n; i++) scanf("%d",val+i); memset(head,-1,sizeof(head)); memset(deg,0,sizeof(deg)); memset(rmvd,0,sizeof(rmvd)); ecnt = 0; for(int i = 0; i < m; i++){ int u,v; scanf("%d%d",&u,&v); addEdge(u,v); addEdge(v,u); } topo(); for(int i = 1; i <= n; i++) pa[i] = i,sum[i] = val[i],cnt[i] = 1; for(int i = 0,M = 2*m; i < M; i += 2){ int u = to[i], v = to[i^1]; if(!rmvd[u] && !rmvd[v]){ int a = fdst(u), b = fdst(v); if(a != b){ pa[a] = b; sum[b] += sum[a]; cnt[b] += cnt[a]; } } } long long ans = 0; for(int i = 1; i <= n ;i++){ int f = fdst(i); if(!rmvd[f]){ if(cnt[f]&1){ ans += sum[f]; } rmvd[f] = true; } } printf("%I64d\n",ans); } return 0; }
2015 ACM/ICPC Asia Regional Changchun Online Pro 1002 (拓扑排序+并查集)
标签:
原文地址:http://www.cnblogs.com/jerryRey/p/4804911.html