跳到正文

剪贴板

剪贴板 sf6csny4

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include <bits/stdc++.h>
using namespace std;
#define inf 1000000000000000
#define V 100010
#define E 5000010
typedef long long int ll;
struct edge {
	int to, next;
	ll capa;
};
int cnt = 0, head[V], n, m; edge node[E];
inline void add(int fir, int nxt, ll w) {
	node[cnt].to = nxt,
		node[cnt].capa = w,
		node[cnt].next = head[fir],
		head[fir] = cnt++;
}
int s, t, dep[V], gap[V], cur[V]; queue<int>que; ll sum = 0;
inline void initing() {
	memset(dep, -1, V * sizeof(int));
	memcpy(cur, head, (t + 1) * sizeof(int));
}
inline void bfs() {
	int fro, ito;
	que.push(t); dep[t] = 0; ++gap[dep[t]];
	while (!que.empty()) {
		fro = que.front(); que.pop();
		for (register int i = head[fro]; i != -1; i = node[i].next) {
			ito = node[i].to;
			if (dep[ito] == -1) {
				dep[ito] = dep[fro] + 1;
				que.push(ito);
				++gap[dep[ito]];
			}
		}
	}
}
ll dfs(int u, ll flow) {
	if (flow == 0 || u == t)return flow; ll used = 0, wei = 0;
	for (register int i = cur[u]; i != -1; i = node[i].next) {
		cur[u] = i;
		if (dep[u] == dep[node[i].to] + 1 && node[i].capa) {
			wei = dfs(node[i].to, min(flow - used, node[i].capa));
			if (wei) {
				node[i].capa -= wei;
				node[i ^ 1].capa += wei;
				used += wei;
			}
		}
		if (used == flow)return used;
	}
	--gap[dep[u]];
	if (!gap[dep[u]])dep[s] = t + 1;
	++gap[++dep[u]];
	return used;
}
ll ISAP() {
	initing(); bfs();
	while (dep[s] < t) {
		sum += dfs(s, inf);
		memcpy(cur, head, (t + 1) * sizeof(int));
	}
	return sum;
}
inline void addE(int u, int v, ll w) {
	add(u, v, w);
	add(v, u, 0);
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(); cout.tie();
	memset(head, -1, V * sizeof(int));
	cin >> m >> n; s = n + 1, t = n + 2;
	for (int i = 1; i <= m; i++)addE(s, i, 1);
	for (int i = m + 1; i <= n; i++)addE(i, t, 1);
	int x, y;
	while (1) {
		cin >> x >> y;
		if (x == -1 && y == -1)break;
		addE(x, y, 1);
	}
	cout << ISAP() << endl;
	for (int i = 1; i <= m; i++) {
		for (int j = head[i]; j != -1; j = node[j].next) {
			if (node[j].capa == 0 && node[j].to != s) {
				cout << i << " " << node[j].to << endl;
				break;
			}
		}
	}
	return 0;
}