
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5438
Ponds
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 2237 Accepted Submission(s): 707
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.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue> using namespace std;
#define ll long long
const int N=; ll p,m,v[N],vis[N],indir[N];
vector<ll>G[N]; ll bfs(ll x)
{
queue<ll>q;
q.push(x);
vis[x]=;
ll k=;
ll sum=v[x];
while (!q.empty())
{ int s=q.front();
q.pop(); //cout<<s<<endl;
k++;
for (int i=; i<G[s].size(); i++)
{
if (!vis[G[s][i]]&&indir[G[s][i]]>=)//删掉的点不可以加进来
{
sum+=v[G[s][i]];
q.push(G[s][i]);
vis[G[s][i]]=;
}
}
}
if (k>=&&k%==)
return sum;
else
return ;
} int main()
{
int T,a,b;
scanf("%d",&T);
while (T--)
{
scanf("%lld%lld",&p,&m);
memset(vis,,sizeof(vis));
memset(G,,sizeof(G));
memset(indir,,sizeof(indir));
for (int i=; i<=p; i++)
{
scanf("%lld",&v[i]);
}
for (int i=; i<=p; i++)
G[i].clear();
for (int i=; i<=m; i++)
{
scanf("%d%d",&a,&b);
G[a].push_back(b);//将b放在a队列的最后一个
G[b].push_back(a);
indir[a]++;
indir[b]++;
}
int j;
for (int i=; i<=p; i++)
{
for ( j=; j<=p; j++)
{
if (indir[j]==||indir[j]==)
{
break;
}
}
if (j>p)
break;
indir[j]=-;
for (int k=; k<G[j].size(); k++)
{
indir[G[j][k]]--;
}
}
ll ans=;
for (int i=; i<=p; i++)//搜遍所有的环
if (!vis[i]&&indir[i]>=)
ans+=bfs(i);
cout<<ans<<endl;
}
return ;
}