随机化RE+CE Dinic代码
查看原帖
随机化RE+CE Dinic代码
124314
lcyxds楼主2020/12/19 15:58
#include <cstdio>
#include <iostream>
#include <cstring>
#define ll long long

using namespace std;

const ll INF = 0x7f7f7f7f7f7f7f7fll;

struct Edge {
	int u;
	ll v;
	int next;
};

int n;
int m;
int s;
int t;
int p[1010];
Edge graph[102010];
int cc = 2;

int ceng[1010];
int queue[1010];
int head;
int tail;

ll res;

void Push(int u, int v, int w) {
	graph[cc].u = v;
	graph[cc].v = w;
	graph[cc].next = p[u];
	p[u] = cc;
	cc++;
}

bool Bfs() {
	head = 0;
	tail = 0;
	queue[0] = s;
	memset(ceng, 0, sizeof(ceng));
	ceng[s] = 1;
	int solo;
	int a;
	int u;
	while (head <= tail) {
		a = queue[head];
		head++;
		solo = p[a];
		while (solo) {
			if (graph[solo].v) {
				u = graph[solo].u;
				if (!ceng[u]) {
					ceng[u] = ceng[a]+1;
//					cout << u << ',' << ceng[u] << endl;
					tail++;
					queue[tail] = u;
				}
			}
			solo = graph[solo].next;
		}
	}
	return ceng[t];
}

ll Dfs(int a, ll have) {
//	cout << "Dfs " << a << ',' << have << endl;
	if (a==t) return have;
//	for (int i = 0; i < 100000000; i++);
	ll res = 0;
	int u;
	int solo = p[a];
	ll v;
	while (solo && have) {
		if (graph[solo].v) {
			u = graph[solo].u;
			if (ceng[u] == ceng[a]+1) {
				v = Dfs(u, min(have, graph[solo].v));
				graph[solo].v-=v;
				graph[solo^1].v+=v;
				res+=v;
				have-=v;
			}
		}
		solo = graph[solo].next;
	}
	if (!res) {
		ceng[a] = 0;
	}
//	cout << res << ',' << endl;
	return res;
}

void Dinic() {
	while (true) {
		if (!Bfs()) {
			return;
		}
		res+=Dfs(s, INF);
	}
}

int main() {
	int u, v;
	int a, b;
 	freopen("P3376.in", "r", stdin);
	scanf("%d%d%d", &a, &b, &m);
	n = a+b+2;
	s = 1;
	t = n;
	for (int i = 2; i < a+2; i++) {
		Push(1, i, 1);
		Push(i, 1, 0);
	}
	for (int i = a+2; i < n; i++) {
		Push(i, n, 1);
		Push(n, i, 0);
	}
	for (int i = 0; i < m; i++) {
		scanf("%d%d", &u, &v);
		Push(u+1, v+a+1, 1);
		Push(v+a+1, u+1, 0);
	}
	Dinic();
//	cout << Bfs() << endl;
	printf("%lld", res);
 	fclose(stdin);
	return 0;
}
2020/12/19 15:58
加载中...