思路:
1. 对于任何代表 Xi,他可以坐在任意一张桌子 Yi 上,抽象出来这个条件就可以方便下面我们建模了;
2. 从源点向 Xi 引弧,容量为代表数目。从 Yi 向汇点引弧,容量为座子所能容纳的人数。从 Xi 分别向每个 Yi 引弧,容量为 1,表示代表对每张桌子都有选择权;
3. 求二分图的最大流即可,如果代表的总数目 = 最大流,则表示每个代表都能找到自己的位置,题目有解,否则无解。
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int MAXN = 500;
const int INFS = 0x3FFFFFFF;
struct edge {
int from, to, cap, flow;
edge(int _from, int _to, int _cap, int _flow)
: from(_from), to(_to), cap(_cap), flow(_flow) {}
};
class Dinic {
public:
void addedge(int u, int v, int cap) {
edges.push_back(edge(u, v, cap, 0));
edges.push_back(edge(v, u, 0, 0));
int m = edges.size();
G[u].push_back(m - 2);
G[v].push_back(m - 1);
}
bool BFS() {
for (int i = 0; i < n; i++)
vis[i] = false, d[i] = 0;
queue<int> Q;
Q.push(s);
vis[s] = true;
while (!Q.empty()) {
int x = Q.front(); Q.pop();
for (int i = 0; i < G[x].size(); i++) {
edge& e = edges[G[x][i]];
if (!vis[e.to] && e.cap > e.flow) {
vis[e.to] = true;
d[e.to] = d[x] + 1;
Q.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x, int aug) {
if (x == t || aug == 0) return aug;
int flow = 0;
for (int i = 0; i < G[x].size(); i++) {
edge& e = edges[G[x][i]];
if (d[e.to] == d[x] + 1) {
int f = DFS(e.to, min(aug, e.cap-e.flow));
if (f == 0) continue;
e.flow += f;
edges[G[x][i]^1].flow -= f;
flow += f;
aug -= f;
if (aug == 0) break;
}
}
return flow;
}
int maxflow(int s, int t) {
this->s = s, this->t = t;
int flow = 0;
while (BFS()) {
flow += DFS(s, INFS);
}
return flow;
}
void cleardata(int n) {
this->n = n;
edges.clear();
for (int i = 0; i < n; i++)
G[i].clear();
}
void print(int m) {
for (int x = 1; x <= m; x++) {
for (int i = 0; i < G[x].size(); i++) {
edge& e = edges[G[x][i]];
if (e.cap > 0 && e.cap == e.flow && e.to != t)
printf("%d ", e.to - m);
}
printf("\n");
}
}
private:
vector<edge> edges;
vector<int> G[MAXN];
int d[MAXN], s, t, n;
bool vis[MAXN];
};
Dinic dc;
int main() {
int m, n;
scanf("%d%d", &m, &n);
int s = 0, t = m + n + 1;
dc.cleardata(t + 1);
int sum = 0;
for (int i = 1; i <= m; i++) {
int a;
scanf("%d", &a);
sum += a;
dc.addedge(s, i, a);
}
for (int i = 1; i <= n; i++) {
int a;
scanf("%d", &a);
dc.addedge(i + m, t, a);
}
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dc.addedge(i, j + m, 1);
int f = dc.maxflow(s, t);
if (f == sum) {
printf("1\n");
dc.print(m);
} else {
printf("0\n");
}
return 0;
}