題目大意:有N個人在收集貼紙。現在給出每個人所擁有的貼紙
然後1這個想要得到更多種類的貼紙,所以他要拿他的貼紙去跟別人換,換的條件是1張交換1張,且你所交換的那張貼紙的種類對方沒有,你想要得到的貼紙的種類對方至少有2張,問最後這個人能得到多少種貼紙
解題思路:一個超級源點,連接貼紙的種類,容量為1這個人所擁有的該種類的貼紙數量
將所有貼紙的種類連接到超級匯點,容量為1
在弄出N-1個點,代表另外的人,如果該貼紙的種類對方沒有,那麼連邊,容量為1,因為只需要1張就夠了(貼紙 –>人)
如果該貼紙對方有至少兩張,那麼連邊,容量為這個人的該貼紙的數量-1(至少要保留一張,人–>貼紙)
然後跑最大流
#include
#include
#include
#include
#include
using namespace std;
#define N 1010
#define INF 0x3f3f3f3f
struct Edge{
int from, to, cap, flow;
Edge() {}
Edge(int from, int to, int cap, int flow) : from(from), to(to), cap(cap), flow(flow) {}
};
struct Dinic{
int n, m, s, t;
vector edges;
vector G[N];
bool vis[N];
int d[N], cur[N];
void init(int n) {
this->n = n;
for (int i = 0; i <= n; i++) {
G[i].clear();
}
edges.clear();
}
void AddEdge(int from, int to, int cap) {
edges.push_back(Edge(from, to, cap, 0));
edges.push_back(Edge(to, from, 0, 0));
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool BFS() {
memset(vis, 0, sizeof(vis));
queue Q;
Q.push(s);
vis[s] = 1;
d[s] = 0;
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (!vis[e.to] && e.cap > e.flow) {
vis[e.to] = true;
d[e.to] = d[u] + 1;
Q.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x, int a) {
if (x == t || a == 0)
return a;
int flow = 0, f;
for (int i = cur[x]; i < G[x].size(); i++) {
Edge &e = edges[G[x][i]];
if (d[x] + 1 == d[e.to] && (f = DFS(e.to, min(a, e.cap - e.flow))) > 0) {
e.flow += f;
edges[G[x][i] ^ 1].flow -= f;
flow += f;
a -= f;
if (a == 0)
break;
}
}
return flow;
}
int Maxflow(int s, int t) {
this->s = s; this->t = t;
int flow = 0;
while (BFS()) {
memset(cur, 0, sizeof(cur));
flow += DFS(s, INF);
}
return flow;
}
};
Dinic dinic;
int n, m, source, sink, cas = 1;
int num[15][30];
void init() {
scanf(%d%d, &n, &m);
memset(num, 0, sizeof(num));
source = 0; sink = n + m;
int x, y;
for (int i = 1; i <= n; i++) {
scanf(%d, &x);
for (int j = 1; j <= x; j++) {
scanf(%d, &y);
num[i][y]++;
}
}
dinic.init(sink);
for (int j = 1; j <= m; j++) {
dinic.AddEdge(source, j, num[1][j]);
dinic.AddEdge(j, sink, 1);
}
for (int i = 2; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (num[i][j] > 1) dinic.AddEdge(m + i - 1, j, num[i][j] - 1);
if (!num[i][j]) dinic.AddEdge(j, m + i - 1, 1);
}
int ans = dinic.Maxflow(source, sink);
printf(Case #%d: %d
, cas++, ans);
}
int main() {
int test;
scanf(%d, &test);
while (test--) {
init();
}
return 0;
}