欧拉图 HDU 3018

题意:

Problem Description

Ant Country consist of N towns.There are M roads connecting the towns.

Ant Tony,together with his friends,wants to go through every part of the country. 

They intend to visit every road , and every road must be visited for exact one time.However,it may be a mission impossible for only one group of people.So they are trying to divide all the people into several groups,and each may start at different town.Now tony wants to know what is the least groups of ants that needs to form to achieve their goal.

Input

Input contains multiple cases.Test cases are separated by several blank lines. Each test case starts with two integer N(1<=N<=100000),M(0<=M<=200000),indicating that there are N towns and M roads in Ant Country.Followed by M lines,each line contains two integers a,b,(1<=a,b<=N) indicating that there is a road connecting town a and town b.No two roads will be the same,and there is no road connecting the same town.

Output

For each test case ,output the least groups that needs to form to achieve their goal.

Sample Input

 

3 3

1 2

2 3

1 3

4 2

1 2

3 4

Sample Output

 

1

2

分析:

题意等价于:

        给你无向图的N个点和M条边,保证这M条边都不同且不会存在同一点的自环边,现在问你至少要几笔才能所有边都画一遍.(一笔画的时候笔不离开纸)

分析:

        首先根据给出的边我们只需要分别处理每个连通分量需要多少笔即可.

        如果该连通分量是一个孤立的点,显然只需要0笔.

        如果该连通分量是一个欧拉图或半欧拉图,只需要1笔.

        现在关键是连通分量并非一个(半)欧拉图时,需要几笔?

        一般性的结论是:

       非(半)欧拉图需要的笔数==该图中奇数度的点数目/2(证明请看---->https://blog.csdn.net/u013480600/article/details/30285541
代码:

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100000+10;
int n,m;
int fa[maxn];
int num[maxn],odd[maxn],degree[maxn];
int findset(int i)
{
    if(fa[i]==-1) return i;
    return fa[i]=findset(fa[i]);
}
int main()
{
    while(scanf("%d%d",&n,&m)==2)
    {
        memset(fa,-1,sizeof(fa));
        memset(num,0,sizeof(num));
        memset(odd,0,sizeof(odd));
        memset(degree,0,sizeof(degree));
        for(int i=0;i<m;i++)
        {
            int u,v;
            scanf("%d%d",&v,&u);//这里u,v颠倒一样。
            degree[v]++;
            degree[u]++;
            u=findset(u), v=findset(v);
            if(u!=v) fa[u]=v;
        }
        for(int i=1;i<=n;i++)
        {
            num[findset(i)]++;      //num[i]=x表以i为根的连通分量中有x个节点
/*这里可能不好理解,举个例子3个点两条边(1->2,1->3按并查集建树)
nump[findest(1)]即num[3]++;
num[findest(2)]即num[3]++;所以以三为根的节点有3个,
这里要注意3所包括的节点(3除外)的联通节点有0个,
即num[2]=0,num[1]=0.仔细想想就知道了。
*/
            if(degree[i]%2) odd[findset(i)]++;//odd[i]=x表以i为根的连通分量中有x个奇度的点
        }
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            if(num[i]<=1) continue;
            else if(odd[i]==0) ans++;
            else if(odd[i]>0) ans+=odd[i]/2;
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/84728404