Ponds
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)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 7Sample Output
21
就是拓扑排序,入度为0的不管,入度为1的删除同时和他相连的顶点入度减一。然后把联通分量的顶点数为奇数的加起来就可以了。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<cstdio>
#include<ctime>
using namespace std;
const int N = 11111;
int n, q;
int a[N];
int b[N];
vector<int>g[N];
bool flag[N];
void f()//拓扑排序
{
int i, j, k;
int flag = 0;//只有更改过,下一次才需要更改
while(!flag)
{
flag = 1;
for(j=1; j<=n; ++j) //遍历所有的结点
{
if(b[j] == 1)
{
b[j]--; //该顶点的入度为-1,防止该顶点被再此遍历到
for(k = 0; k < g[j].size(); k++)
{
if(b[ g[j][k] ] > 0)
{
b[ g[j][k] ]--;
flag = 0;
}
}
}
}
}
}
long long dfs(int v, int& tmp)//返回联通分量的值,tmp得到联通分量的顶点个数
{
tmp++;
flag[v] = 1;
int i;
long long ans = a[v];
for(i = 0; i < g[v].size(); i++)
{
if(b[ g[v][i] ] > 1 && !flag[ g[v][i] ])
{
ans += dfs(g[v][i], tmp);
}
}
return ans;
}
int main(void)
{
int T;
scanf("%d", &T);
while(T--)
{
int i, j;
memset(flag, 0, sizeof(flag));
memset(b, 0, sizeof(b));
scanf("%d%d", &n, &q);
for(i = 1; i <= n; i++) {scanf("%d", &a[i]);g[i].clear();}
while(q--)
{
int x, y;
scanf("%d%d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
b[x]++;
b[y]++;
}
long long ans = 0;
f();
for(i = 1; i <= n; i++)
{
if(!flag[i] && b[i] > 1)
{
int tmp = 0;
long long temp = dfs(i, tmp);
if(tmp&1) ans += temp;
}
}
printf("%lld\n", ans);
}
return 0;
}