ACM: 图论题 poj 1…

来源:互联网 发布:java酒店管理系统程序 编辑:程序博客网 时间:2024/05/18 22:42
COURSES

 

Description

Consider a group of N studentsand P courses. Each student visits zero, one or more than onecourses. Your task is to determine whether it is possible to form acommittee of exactly P students that satisfies simultaneously theconditions:

  • every student in the committee represents a different course (astudent can represent a course if he/she visits thatcourse)
  • each course has a representative in the committee

Input

Your program should read sets ofdata from the std input. The first line of the input contains thenumber of the data sets. Each data set is presented in thefollowing format:

P N
Count1 Student1 1 Student1 2 ...Student1 Count1
Count2 Student2 1 Student2 2 ...Student2 Count2
...
CountP StudentP 1 StudentP 2 ...StudentP CountP

The first line in each data set contains two positive integersseparated by one blank: P (1 <= P <=100) - the number of courses and N (1 <= N<= 300) - the number of students. The next P linesdescribe in sequence of the courses �from course 1 to course P,each line describing a course. The description of course i is aline that starts with an integer Count i (0 <= Counti <= N) representing the number of students visitingcourse i. Next, after a blank, you抣l find the Count i students,visiting the course, each two consecutive separated by one blank.Students are numbered with the positive integers from 1 to N.
There are no blank lines between consecutive sets of data. Inputdata are correct.

Output

The result of the program is onthe standard output. For each input data set the program prints ona single line "YES" if it is possible to form a committee and "NO"otherwise. There should not be any leading blanks at the start ofthe line.

Sample Input

2
3 3
3 1 2 3
2 1 2
1 1
3 3
2 1 3
2 1 3
1 1

Sample Output

YES
NO

 

题意: 每一个学生可能有多个选择去的课程, 但是每个人只能去一个, 问每门课是否都有学生去.

 

解题思路:

     1. 二分匹配

 

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 305

int P, N;
bool g[MAX][MAX], vis[MAX];
int y[MAX];

bool find(int u)
{
 for(int v = 1; v <= N; ++v)
 {
  if( g[u][v]&& !vis[v] )
  {
   vis[v] =true;
   if( y[v] ==-1 || find(y[v]) )
   {
    y[v]= u;
    returntrue;
   }
  }
 }
 return false;
}

bool Edmonds()
{
 int result = 0;
 memset(y, -1, sizeof(y));
 for(int u = 1; u <= P; ++u)
 {
  memset(vis, false,sizeof(vis));
  if( find(u) ) result++;
 }
 if(result == P) return true;
 else return false;
}

int main()
{
// freopen("input.txt", "r", stdin);
 int caseNum;
 scanf("%d", &caseNum);
 while( caseNum-- )
 {
  scanf("%d %d",&P, &N);
  int num, v;
  memset(g, false,sizeof(g));
  for(int i = 1; i<= P; ++i)
  {
   scanf("%d",&num);
   for(int j =1; j <= num; ++j)
   {
    scanf("%d",&v);
    g[i][v]= true;
   }
  }

  if( Edmonds() )printf("YES\n");
  else printf("NO\n");
 }
 return 0;
}

0 0
原创粉丝点击