Descriptionphp
Frank N. Stein is a very conservative high-school teacher. He wants to take some of his students on an excursion, but he is afraid that some of them might become couples. While you can never exclude this possibility, he has made some rules that he thinks indicates a low probability two persons will become a couple:ios
So, for any two persons that he brings on the excursion, they must satisfy at least one of the requirements above. Help him find the maximum number of persons he can take, given their vital information.算法
Inputui
The first line of the input consists of an integer T ≤ 100 giving the number of test cases. The first line of each test case consists of an integer N ≤ 500 giving the number of pupils. Next there will be one line for each pupil consisting of four space-separated data items:this
No string in the input will contain more than 100 characters, nor will any string contain any whitespace.spa
二分圖最大匹配,使用匈牙利算法解決。code
根據性別將學生分爲兩個不交集合。orm
求出最大匹配數m後,n - m即爲所求。blog
AC Code:ip
1 #include <iostream> 2 #include <queue> 3 #include <cstdio> 4 #include <cstring> 5 #include <cmath> 6 using namespace std; 7 #define clr(a, i) memset(a, i, sizeof(a)) 8 #define FOR0(i, n) for(int i = 0; i < n; ++i) 9 #define FOR1(i, n) for(int i = 1; i <= n; ++i) 10 #define sf scanf 11 #define pf printf 12 13 const int MAXN = 505; 14 struct Node 15 { 16 int h; 17 char gen; 18 char mus[102]; 19 char spo[102]; 20 void input() { 21 scanf("%d %c %s %s", &h, &gen, mus, spo); 22 } 23 bool satisfy(Node &y) const{ 24 return gen != y.gen && fabs(h - y.h) <= 40 && !strcmp(mus, y.mus) && 25 strcmp(spo, y.spo); 26 } 27 }pup[MAXN]; 28 int n; 29 vector<int> female, male; 30 bool adj[MAXN][MAXN]; 31 int match[MAXN]; 32 bool vis[MAXN]; 33 34 void addEdge(int i) 35 { 36 adj[i][i] = false; 37 for (int j = 0; j < i; ++j){ 38 adj[i][j] = adj[j][i] = pup[i].satisfy(pup[j]); 39 } 40 } 41 42 bool findCrossPath(int v) 43 { 44 for(int i = 0; i < n; ++i) 45 { 46 if(adj[v][i] == true && vis[i] == false) 47 { 48 vis[i] = true; 49 if(match[i] == -1 || findCrossPath(match[i])) 50 { 51 match[i] = v; 52 return true; 53 } 54 } 55 } 56 return false; 57 } 58 59 int Hungary() 60 { 61 int cnt = 0; 62 memset(match, -1, sizeof(match)); 63 for(vector<int>::iterator it = male.begin(); it != male.end(); ++it) 64 { 65 memset(vis, false, sizeof(vis)); 66 if(match[*it] == -1 && findCrossPath(*it)) 67 { 68 ++cnt; 69 } 70 } 71 return cnt; 72 } 73 74 int main() 75 { 76 int t; 77 scanf("%d", &t); 78 while(t--) 79 { 80 female.clear(); 81 male.clear(); 82 scanf("%d", &n); 83 for(int i = 0; i < n; ++i) 84 { 85 pup[i].input(); 86 if(pup[i].gen == 'F') female.push_back(i); 87 else male.push_back(i); 88 addEdge(i); 89 } 90 printf("%d\n", n - Hungary()); 91 } 92 return 0; 93 }