思路:网络流,建图如果客户x不买宠物y,就把那点边标记为0,否则标记为1,然后求该图的最大流。
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; const int INF = 0x3f3f3f3f; const int N = 210; int cap[N][N] ,flow[N][N]; int a[N],p[N]; int n,m,e; int maxflow(int s,int t) { int f = 0; queue<int> que; memset(flow, 0, sizeof(flow)); while(true) { memset(a,0,sizeof(a)); a[s] = INF; que.push(s); while(!que.empty()) { int u = que.front(); que.pop(); for(int v = 0; v <= t; v++) { if(!a[v] && cap[u][v] > flow[u][v]) { p[v] = u; que.push(v); a[v] = min(a[u],cap[u][v] - flow[u][v]); } } } if(a[t] == 0) { break; } for(int u = t; u != s; u = p[u]) { flow[p[u]][u] += a[t]; flow[u][p[u]] -= a[t]; } f += a[t]; } return f; } void init() { memset(cap,0,sizeof(cap)); for(int u = 1; u <= n; u++) { for(int v = n+1; v <= n+m; v++) { cap[u][v] = 1; } } for(int v = 1; v <= n; v++) { cap[0][v] = 1; } int t = n + m + 1; for(int u = n+1; u <= n+m; u++) { cap[u][t] = 1; } } int main() { int T; int u,v; int cas = 1; scanf("%d",&T); while(T--) { scanf("%d%d%d",&n,&m,&e); init(); for(int i = 0; i < e; i++) { scanf("%d%d",&u,&v); v += n; cap[u][v] = 0; } int ans = maxflow(0, n + m + 1); printf("Case %d: %d\n",cas++,ans); } return 0; }