Ant TripTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4939 Accepted Submission(s): 1928 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 Hint New ~~~ Notice: if there are no road connecting one town ,tony may forget about the town. In sample 1,tony and his friends just form one group,they can start at either town 1,2,or 3. In sample 2,tony and his friends must form two group. |
题目意思就是给你一个图(n个点,m条边) 每条边只能走一次,要走几次才能走完所有的边 (一笔画问题),并且忽略到不了的点
用欧拉图来解决这一类问题,要画的笔数就是奇数点的个数/2;
因为不是联通图,所以要用并查集来维护连通图。
#include<bits/stdc++.h>
using namespace std;
#define mem(a) memset(a,0,sizeof(a));
const int maxn=1e5+5;
int a[maxn],o[maxn],x,y,n,m,f[maxn],use[maxn],cnt;
int find(int x)
{
while(x!=f[x])
{
x=f[x]=f[f[x]];
}
return x;
}//并查集
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
mem(a);
mem(o);
mem(use);
for(int i=1;i<=n;i++) f[i]=i;//初始化
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
a[x]++;
a[y]++;//标记经过这个点的次数
if(find(x)!=find(y))
{
f[find(x)]=find(y);//如果不是连通的 那么就让他们连通(并查集)
}
}
vector<int>v;
for(int i=1;i<=n;i++)
{
int q=find(i);
if(use[q]==0)//并查集中以这个点为爸爸的连通图没有用过
{
use[q]=1;//标记用过
v.push_back(q);//入vector
}
if(a[i]%2)
{
o[q]++;//在这个连通图中奇数点的个数
}
}
cnt=0;
for(int i=0;i<v.size();i++)//一个一个连通图的来
{
int k=v[i];
if(a[k]==0) continue;//如果这个点根本没来过(根据题意要忽略)
if(o[k]==0) cnt++;//奇数点的个数为0,那么这个连通图就可以一笔画出来
else cnt+=o[k]/2;//不然的话就要画奇数点的个数/2笔(一笔画的连通图中最多有俩个奇数点)
}
printf("%d\n",cnt);
}
return 0;
}