@Chilling
2017-02-16T17:54:02.000000Z
字数 1865
阅读 1027
二分图
Description
the second year of the university somebody started a study on the romantic relations between the students. The relation “romantically involved” is defined between one girl and one boy. For the study reasons it is necessary to find out the maximum set satisfying the condition: there are no two students in the set who have been “romantically involved”. The result of the program is the number of students in such a set.
The input contains several data sets in text format. Each data set represents one set of subjects of the study, with the following description:
Input
the number of students
the description of each student, in the following format
student_identifier:(number_of_romantic_relations) student_identifier1 student_identifier2 student_identifier3 ...
or
student_identifier:(0)
Output
The student_identifier is an integer number between 0 and n-1, for n subjects.
For each given data set, the program should write to standard output a line containing the result.
Sample Input
7
0: (3) 4 5 6
1: (2) 4 6
2: (0)
3: (0)
4: (2) 0 1
5: (1) 0
6: (2) 0 1
3
0: (2) 1 2
1: (1) 0
2: (1) 0
Sample Output
5
2
最大独立集:二分图最大独立集合 = 节点数 - 最大匹配数
题意:首先输入n,表示有n个人,然后下面有n行,每行开头先输入这个人的编号(人的编号是从0开始的),按题目的格式,括号里面是他喜欢的人的个数,后面是喜欢的人的编号。问满足最大的匹配之后,还有几只单身狗。
有意思的是,案例中出现a喜欢b,b喜欢c,同时a也喜欢c的情况,a和c应该是同性吧(///▽///)分析:用二分图模板求得最大匹配数,用n减去最大匹配数目的一半。
#include<stdio.h>
#include<vector>
#include<string.h>
using namespace std;
int n,vis[500],p[500],sum;
vector<int>v[500];
int match(int i)
{
int l=v[i].size();
for(int j=0;j<l;j++)
{
if(vis[v[i][j]]==1)
continue;
vis[v[i][j]]=1;
if(p[v[i][j]]==-1||match(p[v[i][j]]))
{
p[v[i][j]]=i;
return 1;
}
}
return 0;
}
int ans()
{
int i;
sum=0;
for(i=0;i<n;i++)
{
memset(vis,0,sizeof(vis));
if(match(i)==1)
sum++;
}
return n-sum/2;
}
int main()
{
int i,x,y,c;
char ch[11];
while(scanf("%d",&n)!=EOF)
{
memset(ch,0,sizeof(ch));
memset(p,-1,sizeof(p));
for(i=0;i<n;i++)
{
scanf("%d:",&x);
scanf("%s",ch);
if(sscanf(ch,"(%d)",&c)==1)
{
while(c--)
{
scanf("%d",&y);
// printf("%d %d\n",x,y);
v[x].push_back(y);
}
}
}
printf("%d\n",ans());
for(int i=0;i<=n;i++)
v[i].clear();
}
return 0;
}