Ponds
Problem Description
Betty owns a lot of ponds, some of them are connected with other ponds by pipes, and there will not be more than one pipe between two ponds. Each pond has a value
v .
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
Input
The first line of input will contain a number
T(1≤T≤30) which is the number of test cases.
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.
Output
For each test case, output the sum of the value of all connected components consisting of odd number of ponds after removing all the ponds connected with less than two pipes.
Sample Input
1
7 7
1 2 3 4 5 6 7
1 4
1 5
4 5
2 3
2 6
3 6
2 7
p个节点,m个连通。去除掉不连通的,以及只有1条连通的。剩下的如果奇数个连通就加上价值,偶数个就不加;输出结果。具体如下:
#include<cstdio>
#include<cstring>
#include<vector>
#include<iostream>
using namespace std;
vector <int> n[10010];
int g[10010],f[10010],ns[10010],xx;//xx已经遍历的节点个数
long long sum,sum2;
void DFS(int z){//深搜
xx++;
f[z]=1;
sum2+=g[z];
for(int i=0;i<n[z].size();i++)
if(!f[n[z][i]]) DFS(n[z][i]);
}
int main()
{
int T,p,m,x,y;
scanf("%d",&T);
while(T--){
sum = xx = 0;
memset(f,0,sizeof(f));//初始化
memset(g,0,sizeof(g));//初始化
memset(ns,0,sizeof(ns));//初始化
for(int i=0;i<10010;i++)
n[i].clear();//初始化
scanf("%d%d",&p,&m);
for(int i=1;i<=p;i++)
scanf("%d",&g[i]);
for(int i=0;i<m;i++){
scanf("%d%d",&x,&y);
n[x].push_back(y);
n[y].push_back(x);
ns[x]++;
ns[y]++;
}
bool key=true;
while(key){
key=false;
for(int i=1;i<=p;i++)
if(ns[i]==1||ns[i]==0){
key=true;
f[i]=1;//当作已经遍历过
for(int j=0;j<n[i].size();j++)
ns[n[i][j]]--;
ns[i]=-1;
}
}
for(int i=1;i<=p;i++){
if(!f[i]){
sum2=xx=0;
DFS(i);
if(xx%2==1)//连通奇数个
sum+=sum2;
}
}
printf("%lld\n",sum);
}
return 0;
}