标签:hdu3018 ant trip 并查集
Ant Trip
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1826 Accepted Submission(s): 702
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个边,问要遍历一遍所有的边,需要的最小group数目。
求一个图中最少几笔画,利用欧拉回路性质,首先得到图的每个强连通分支,然后计算每个强连通分支每个是否都是偶数度是的话,一笔解决,否的话,需要奇数度节点个数的1/2笔解决。(当一个节点度数为奇数时,我们只需要令它的度数为1,因为偶数的话直接抵消了,最后判断一个scc中未1的节点个数,除以2就得到该scc的最小笔画了)
代码:
#include <stdio.h>
#include <string.h>
#define SIZE 100100
int f[SIZE] , deg[SIZE] , ver[SIZE] ;
bool vis[SIZE] ;
int n , m ;
int find(int pos)
{
int r = pos ;
while(r != f[r])
r = f[r] ;
int temp ;
while(pos != r)
{
temp = f[pos] ;
f[pos] = r ;
pos = temp ;
}
return r ;
}
void init()
{
for(int i = 0 ; i <= n ; ++i)
{
f[i] = i ;
}
memset(deg,0,sizeof(deg)) ;
memset(ver,0,sizeof(ver)) ;
memset(vis,false,sizeof(vis)) ;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
init() ;
for(int i = 0 ; i < m ; ++i)
{
int x, y ;
scanf("%d%d",&x,&y) ;
int fx = find(x) , fy = find(y) ;
deg[x]++ , deg[y]++ ;
if(fx!=fy)
{
f[fx] = fy ;
}
}
bool flag = true ;
for(int i = 1 ; i<= n ; ++i)
{
int fx = find(i) ;
if(deg[i]%2 == 1)
{
ver[fx]++ ;
}
}
int cnt = 0 ;
for(int i = 1 ; i <= n ; ++i)
{
if(deg[i] == 0)
continue ;
int fx = find(i) ;
if(!vis[fx])
{
vis[fx] = true ;
if(!ver[fx])
cnt ++ ;
else
cnt+=ver[fx]/2 ;
}
}
printf("%d\n",cnt) ;
}
}
与君共勉hdu 3018 Ant Trip 算是一道欧拉通路的题目吧~
标签:hdu3018 ant trip 并查集
原文地址:http://blog.csdn.net/lionel_d/article/details/45307741