HDU 5438.Ponds【2015 ACM/ICPC Asia Regional Changchun Online】【DFS】9月13

来源:互联网 发布:apache 源码下载linux 编辑:程序博客网 时间:2024/05/22 12:47

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(1T30) 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(1p104) which represents the number of ponds she owns, and the other is the number m(1m105) which represents the number of pipes.

The next line contains p numbers v1,...,vp, where vi(1vi108) 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
17 71 2 3 4 5 6 71 41 54 52 32 63 62 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;}


0 0
原创粉丝点击