题解 UVA12168 Cat vs. Dog
Posted colazcy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了题解 UVA12168 Cat vs. Dog相关的知识,希望对你有一定的参考价值。
Solution UVA12168 Cat vs. Dog
题目大意:给定\(n\)个人,有\(c\)只猫和\(d\)只狗.每个人会喜欢一只猫/狗,并且讨厌一只狗/猫.求一种方案让尽可能多的人满意(喜欢的动物出现,讨厌的不出现)
分析:这不就是二分图最大点独立集的模板吗.如果
\(u\)喜欢的是\(v\)讨厌的或者\(u\)讨厌的是\(v\)喜欢的,就要连边\((u,v)\)因为只有喜欢不同动物的人才可能有连边,所以这个图是二分图
两个人之间没有连边就代表他们的要求可以同时满足(都满意),跑一次二分图最大点独立集即可
注意毒瘤的输入!!!以及连边的顺序(要么猫爱好者连狗爱好者,要么反之)
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int INF = 0x7fffffff;
const int maxn = 1024;
const int maxm = (1024 * 1024 + 2048) << 1;
struct Edge
int from,to,cap,flow;
Edge() = default;
Edge(int a,int b,int c,int d):from(a),to(b),cap(c),flow(d)
Edges[maxm];
int head[maxn],nxt[maxm],tot = 1;
inline void clear()
memset(head,0,sizeof(head));
memset(nxt,0,sizeof(nxt));
tot = 1;
inline void addedge(int from,int to,int cap)
Edges[++tot] = Edge(from,to,cap,0);
nxt[tot] = head[from];
head[from] = tot;
Edges[++tot] = Edge(to,from,0,0);
nxt[tot] = head[to];
head[to] = tot;
int d[maxn];
inline bool bfs(int s,int t)
memset(d,-1,sizeof(d));
d[s] = 0;
queue<int> Q;
Q.push(s);
while(!Q.empty())
int u = Q.front();Q.pop();
for(int i = head[u];i;i = nxt[i])
Edge &e = Edges[i];
if(e.cap > e.flow && d[e.to] == -1)
d[e.to] = d[u] + 1;
Q.push(e.to);
return d[t] != -1;
int cur[maxn];
inline int dfs(int u,int a,int t)
if(u == t || a == 0)return a;
int ret = 0,f;
for(int &i = cur[u];i;i = nxt[i])
Edge &e = Edges[i];
if(d[u] + 1 == d[e.to] && (f = dfs(e.to,min(a,e.cap - e.flow),t)) > 0)
ret += f;
Edges[i].flow += f;
Edges[i ^ 1].flow -= f;
a -= f;
if(a == 0)break;
return ret;
inline int maxflow(int s,int t)
int ret = 0;
while(bfs(s,t))
memcpy(cur,head,sizeof(head));
ret += dfs(s,0x7fffffff,t);
return ret;
struct Person
string like,hate;
person[maxn];
int t,cat,dog,n,cnt;
inline void solve()
clear();
cin >> cat >> dog >> n;
for(int i = 1;i <= n;i++)
cin >> person[i].like >> person[i].hate;
int s = n + n + 1,t = n + n + 2;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
if((person[i].like[0] != person[j].like[0]) && (person[i].like == person[j].hate || person[i].hate == person[j].like))
if(person[i].like[0] == 'C')addedge(i,j + n,1);
else if(person[j].like[0] == 'C')addedge(j,i + n,1);
for(int i = 1;i <= n;i++)
if(person[i].like[0] == 'C')
addedge(s,i,1);
for(int i = 1;i <= n;i++)
if(person[i].like[0] == 'D')
addedge(i + n,t,1);
cout << n - maxflow(s,t) << endl;
int main()
#ifdef LOCAL
freopen("fafa.in","r",stdin);
freopen("fafa.out","w",stdout);
#else
ios::sync_with_stdio(false);
#endif
cin >> t;
while(t--)
solve();
return 0;
以上是关于题解 UVA12168 Cat vs. Dog的主要内容,如果未能解决你的问题,请参考以下文章
hdu2768Cat vs. Dog (反建法,最大独立集)