Ponds
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 3234 Accepted Submission(s): 997
Now Betty wants to remove some ponds because she does not have enough money. But each time when she removes a pond, she can only remove the ponds which are connected with less than two ponds, or the pond will explode.
Note that Betty should keep removing ponds until no more ponds can be removed. After that, please help her calculate the sum of the value for each connected component consisting of a odd number of ponds
For each test case, the first line contains two number separated by a blank. One is the number p(1≤p≤104) which represents the number of ponds she owns, and the other is the number m(1≤m≤105) which represents the number of pipes.
The next line contains p numbers v1,...,vp, where vi(1≤vi≤108) indicating the value of pond i.
Each of the last m lines contain two numbers a and b, which indicates that pond a and pond b are connected by a pipe.
7 7
1 2 3 4 5 6 7
1 4
1 5
4 5
2 3
2 6
3 6
2 7
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include <vector>
using namespace std;
const int maxn = 1e4+;
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 = ; i<=p; i++)
if(in[i] <= ) //还有度数为0的点
q.push(i);
while(!q.empty())
{
int temp = q.front();
q.pop();
ans[temp]++;
for(int j = ; j<g[temp].size(); j++)
{
int vv = g[temp][j];
if(in[vv]<=) continue; //z这里有坑,否则就陷入死循环了。
in[vv]--;
if(in[vv] <= )
q.push(vv);
}
}
}
void dfs(int s,int& count,long long& sum)
{
if(ans[s]>||vis[s]) return;
vis[s] = ;
for(int i = ; i<g[s].size(); i++)
{
int vv = g[s][i];
if(ans[vv] == && !vis[vv])
{
count++;
sum += v[vv];
dfs(vv,count,sum);
}
}
}
int main()
{
scanf("%d",&t);
while(t--)
{
memset(ans,,sizeof(ans));
memset(in,,sizeof(in));
memset(vis,,sizeof(vis));
scanf("%d %d",&p,&m);
for(int i = ; i<=p; i++)
{
scanf("%d",&v[i]);
}
int l,r;
for(int i = ; i<=p; i++) g[i].clear();
for(int i = ; 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 = ,sum1 = ;
int count = ;
for(int i = ; i<=p; i++)
{
if(ans[i] == &&!vis[i])
{
sum1 = v[i];
count = ;
dfs(i,count,sum1);
if(count% == ) sum += sum1;
}
}
printf("%I64d\n",sum); }
return ;
}
/*
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
*/