标签:
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 3234 Accepted Submission(s): 997
#include <iostream> #include<cstdio> #include<cstring> #include<queue> #include<algorithm> #include <vector> using namespace std; const int maxn = 1e4+5; vector<int> g[maxn]; int v[maxn]; int ans[maxn]; int vis[maxn]; int in[maxn]; int t; int p,m; int cnt; void toposort() { queue<int> q; for(int i = 1; i<=p; i++) if(in[i] <= 1) //还有度数为0的点 q.push(i); while(!q.empty()) { int temp = q.front(); q.pop(); ans[temp]++; for(int j = 0; j<g[temp].size(); j++) { int vv = g[temp][j]; if(in[vv]<=1) continue; //z这里有坑,否则就陷入死循环了。 in[vv]--; if(in[vv] <= 1) q.push(vv); } } } void dfs(int s,int& count,long long& sum) { if(ans[s]>0||vis[s]) return; vis[s] = 1; for(int i = 0; i<g[s].size(); i++) { int vv = g[s][i]; if(ans[vv] == 0&& !vis[vv]) { count++; sum += v[vv]; dfs(vv,count,sum); } } } int main() { scanf("%d",&t); while(t--) { memset(ans,0,sizeof(ans)); memset(in,0,sizeof(in)); memset(vis,0,sizeof(vis)); scanf("%d %d",&p,&m); for(int i = 1; i<=p; i++) { scanf("%d",&v[i]); } int l,r; for(int i = 1; i<=p; i++) g[i].clear(); for(int i = 1; i<=m; i++) { scanf("%d %d",&l,&r); g[l].push_back(r); g[r].push_back(l); in[l]++; in[r]++; } toposort(); long long sum = 0,sum1 = 0; int count = 0; for(int i = 1; i<=p; i++) { if(ans[i] == 0&&!vis[i]) { sum1 = v[i]; count = 1; dfs(i,count,sum1); if(count%2 == 1) sum += sum1; } } printf("%I64d\n",sum); } return 0; } /* 312 7 10 1 20 300 400 500 1000 5000 1 2 1 3 1 4 2 3 2 4 3 4 5 6 6 7 5 7 3 6 2 1 10 20 1 2 3 2 10 100 1000 1 2 1 3 3 1 10 100 1000 1 2 */
标签:
原文地址:http://www.cnblogs.com/littlepear/p/5668026.html