Ponds
Total Submission(s): 3851 Accepted Submission(s): 582
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
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 <algorithm>
#include <vector>
#define SIZE 10050
using namespace std;
struct node
{
int v;
};
vector<int >q[SIZE];
int n,m;
int no[SIZE];
int d[SIZE],vis[SIZE];
long long num,ans,cnt;
//int flag[SIZE];
void work();
void delet(int );
void init()
{
memset(d,0,sizeof(d));
for(int i = 0 ; i <= n ; i ++)
q[i].clear();
memset(no,0,sizeof(no));
memset(vis,0,sizeof(vis));
cnt = num = ans = 0;
}
void input()
{
scanf("%d%d",&n,&m);
for(int i = 1 ; i <= n ; i ++)
{
scanf("%d",&no[i]);
}
int u,v;
for(int i = 0 ; i < m ; i ++)
{
scanf("%d%d",&u,&v);
q[u].push_back(v);
q[v].push_back(u);
d[u] ++, d[v] ++;
}
}
void delet(int i)
{
d[i] --;
vis[i] = 1;
}
void work(int p)
{
delet(p);
for(int i = 0 ; i <= (int)q[p].size()-1 ; i++)
{
int j = q[p][i];
if(vis[j])continue;
d[j]--;
if(d[j] <= 1)
work(j);
}
}
void dfs(int i)
{
for(int j = 0 ; j <= (int)q[i].size()-1 ; j ++)
{
int x = q[i][j];
if(!vis[x])
{
num += no[x];
vis[x] = 1;
cnt ++;
dfs(x);
}
}
}
int main()
{
// freopen("in.txt","r",stdin);
int t ;
scanf("%d",&t );
while(t --)
{
init();
input();
for(int i = 1 ; i <= n ; i ++)
{
if(d[i]<=1 && vis[i] == 0)work(i);
}
/* for(int i = 1; i <= n ; i ++)
{
printf("%d:%d\n",i,d[i]);
}*/
for(int i = 1 ; i <= n ; i ++)
{
num = cnt = 0;
if(!vis[i])
{
num += no[i];
cnt ++;
vis[i] = 1;
dfs(i);
}
if(cnt%2)
{
ans += num ;
}
}
printf("%I64d\n",ans);
}
return 0;
}