Time Limit: 1500/1000 MS (Java/Others)
Memory Limit: 131072/131072 K (Java/Others)
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<cstdio>
#include<cstring>
#include<algorithm> using namespace std; #define ll long long
#define push_back pb const int maxp=1e4+;
const int maxm=1e5+; struct Edge
{
int to,next;
};
Edge edge[maxm<<]; int head[maxp];
int tot;
bool vis[maxp];
int in[maxp];
ll v[maxp]; void addedge(int u,int v)
{
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
} ll solve(int ,int );
void dfs(int );
void dfs1(int ,int &,ll &); int main()
{
int test;
scanf("%d",&test);
while(test--){
tot=;
memset(head,-,sizeof head);
memset(in,,sizeof in); int p,m;
scanf("%d %d",&p,&m);
for(int i=;i<=p;i++)
scanf("%I64d",&v[i]);
int u,v;
for(int i=;i<m;i++){
scanf("%d %d",&u,&v);
addedge(u,v);
addedge(v,u);
in[u]++;
in[v]++;
} printf("%I64d\n",solve(p,m));
}
return ;
} ll solve(int p,int m)
{
memset(vis,false,sizeof vis); for(int i=;i<=p;i++){
if(!vis[i]&&in[i]<){
in[i]--;
dfs(i);
}
} ll ret=;
memset(vis,false,sizeof vis);
int num;
ll sum;
for(int i=;i<=p;i++){
if(!vis[i]&&in[i]>){
num=;
sum=;
dfs1(i,num,sum);
if(num%)
ret+=sum;
}
}
return ret;
} void dfs(int u)
{
vis[u]=true;
for(int i=head[u];~i;i=edge[i].next){
int v=edge[i].to;
if(vis[v])
continue;
in[v]--;
if(in[v]<){
in[v]--;
dfs(v);
}
}
} void dfs1(int u,int &num,ll &sum)
{
vis[u]=true;
num++;
sum+=v[u];
for(int i=head[u];~i;i=edge[i].next){
int v=edge[i].to;
if(vis[v]||in[v]<)
continue;
dfs1(v,num,sum);
}
}