跳到正文

剪贴板

剪贴板 ckx2fyso

原文
剪贴板信息

剪贴板信息

收录
更新
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, vis[V]; 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 (u == t || flow == 0)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] = n + 1;
	++gap[++dep[u]];
	return used;
}
ll ISAP() {
	initing(); bfs();
	while (dep[s] < n) {
		sum += dfs(s, inf);
		memcpy(cur, head, (t + 1) * sizeof(int));
	}
	return sum;
}
void print(int v){
	if(vis[v])return;
	vis[v] = true; int u;
	cout << v << " ";
	for(int i = head[v]; i != -1; i = node[i].next){
		u = node[i].to;
		if(!(i & 1) && !node[i].capa && u != s)if(!vis[u - n])print(u - n);
	}
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(); cout.tie();
	memset(head, -1, V * sizeof(int));
	cin >> n >> m; s = n * 2 + 1, t = n * 2 + 2;
	int u, v;
	for(int i = 1; i <= n; i++){
		add(s, i, 1); add(i, s, 0);
		add(i + n, t, 1); add(t, i + n, 0);
	}
	for(int i = 1; i <= m; i++){
		cin >> u >> v;
		add(u, v + n, 1);
		add(v + n, u, 0);
	}
	int mflow = n - ISAP();
	for(int i = 1; i <= n; i++){
		if(!vis[i]){
			print(i);
			cout << endl;
		}
	}
	cout << mflow;
	return 0;
}