【打CF,学算法——三星级】CodeForces 216B Forming Teams (图论)
扫描二维码
随时随地手机看文章
【CF简介】
提交链接:CF 216B
题面:
B. Forming Teams time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard outputOne day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.
We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B is an archenemy to student A.
The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.
Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.
InputThe first line contains two integers n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of students and the number of pairs of archenemies correspondingly.
Next m lines describe enmity between students. Each enmity is described as two numbers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the indexes of the students who are enemies to each other. Each enmity occurs in the list exactly once. It is guaranteed that each student has no more than two archenemies.
You can consider the students indexed in some manner with distinct integers from 1 to n.
OutputPrint a single integer — the minimum number of students you will have to send to the bench in order to start the game.
Examples Input5 4 1 2 2 4 5 3 1 4Output
1Input
6 2 1 4 3 4Output
0Input
6 6 1 2 2 3 3 1 4 5 5 6 6 4Output
2
--------------------------------------------------------------------------------------做完再看------------------------------------------------------------------------------------------------------------------------------
题意:
给定n个朋友,m个敌对关系。敌对关系是相互的,即a和b是敌对的,那么b和a也是敌对的,具有敌对关系的两个人不能在一个小组,一个人最多只有两个敌对对象。现在要求将所有人分成两个小组,使得两组人数相同,且内部不具备敌对关系,且做板凳(即未被选中的人的数量尽量少)。
解题:
将题目给定的敌对关系构造成图,可以发现,联通块要么是环,要么是链,要么就是孤立点(因为一个点最多只有2的度数)。分析可以比较容易得出,奇数长度的环,必须牺牲一个人做板凳,因为选出的len-1人分为两个小组,必有一人与两个小组的人都存在敌对关系,故而找奇环,发现则做板凳人数数量加一。如果是链,可以i,i+1分别分配给两个小组,就不会出现敌对关系,但奇数链会损失一个,但不同链之间无敌对关系,因此可以链接所有链,最终链长度为奇数,则损失一个。
注意:找奇环的过程,开始写错了,应该是计算一个联通块上的总度数,并记录是否出现了度数为1或者为0的点,没有则判定为环,奇环的总度数/2是奇数,可以通过这点判断奇环。
代码:
#include
#include
#include
#include
#include
#include