題意:給定n個學生和每個學生與其他人之間的關係,關係只能在男女之間存在,求最大的集合:集合內任意兩個學生都沒有關係,即最大獨立集。
分析:獨立數+點覆蓋數 = N,所以求出匹配數即可。
Ps:對於雙向邊剛開始我只保存了一條邊,結果WA了,因爲沒有分成男女兩個集合,所以求出來的有問題;如果保存雙向邊,求出最大匹配除以2即可。
附上一組數據:
4
0: (2) 1 3
1: (2) 0 2
2: (2) 1 3
3: (2) 0 2
正確答案是2,而錯誤的代碼得到的答案是1。
以下附上代碼:
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cctype>
#include <cmath>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 505;
int n;
int g[maxn][maxn];
int cx[maxn],cy[maxn];
bool vis[maxn];
void input()
{
int i,j;
int u,v;
int k;
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
g[i][j] = 0;
}
}
for(i = 0; i < n; i++){
scanf("%d: (%d)",&u,&k);
for(j = 0; j < k; j++){
scanf("%d",&v);
g[u][v] = 1;
}
}
}
int path(int u)
{
for(int v = 0; v < n; v++){
if(g[u][v] && !vis[v]){
vis[v] = 1;
if(cy[v] == -1 || path(cy[v])){
cx[u] = v;
cy[v] = u;
return 1;
}
}
}
return 0;
}
int maxMatch()
{
fill(cx,cx+n,-1);
fill(cy,cy+n,-1);
int res = 0;
for(int i = 0; i < n; i++){
if(cx[i] == -1){//未匹配
fill(vis,vis+n,0);
res += path(i);
}
}
return res/2;
}
void solve()
{
printf("%d\n",n-maxMatch());
}
int main()
{
while(scanf("%d",&n) != EOF){
input();
solve();
}
return 0;
}