萌新小姐姐初学dinic,求助二分图匹配模板题
查看原帖
萌新小姐姐初学dinic,求助二分图匹配模板题
200930
QianianXY楼主2021/2/17 10:32

RT. 50分,求dalao看一下错误。

感激不尽

#include <bits/stdc++.h>
#define rei register ll
#define maxn 20005
#define maxm 200005
using namespace std;
typedef long long ll;

struct edge
{
	ll nxt, v, w;
} e[maxm];

ll T, n, a[maxn], head[maxn], cnt = 1, cur[maxn], all, s = 0, t, dep[maxn];

template <typename T> inline void read(T &x)
{
	x = 0; ll f = 1; char ch = getchar();
	while (!isdigit(ch)) {if (ch == '-') f = -f; ch = getchar();}
	while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
	x *= f;
}

inline void add_edge(ll u, ll v, ll w)
{
	e[++cnt].nxt = head[u];
	head[u] = cnt;
	e[cnt].v = v;
	e[cnt].w = w;
}

inline void Clear()
{
	memset(head, 0, sizeof(head));
	memset(cur, 0, sizeof(cur));
	memset(a, 0, sizeof(a));
	all = 0; cnt = 1;
}

inline bool Bfs()
{
	queue<ll> Q;
	memset(dep, 0, sizeof(dep));
	dep[s] = 1;
	Q.push(s);
	while (Q.size())
	{
		ll u = Q.front(); Q.pop();
		cur[u] = head[u];
		for (rei i = head[u]; i; i = e[i].nxt)
		{
			ll v = e[i].v;
			if (!dep[v] && e[i].w)
			{
				dep[v] = dep[u] + 1;
				Q.push(v);
			}
		}
	}
	return dep[t] != 0;
}

inline ll Dfs(ll u, ll flow)
{
	if (u == t) return flow;
	ll rest = flow;
	for (rei i = cur[u]; i; i = e[i].nxt)
	{
		ll v = e[i].v; cur[u] = i;
		if (dep[v] == dep[u] + 1 && e[i].w)
		{
			ll tmp = Dfs(v, min(e[i].w, rest));
			e[i].w -= tmp;
			e[i ^ 1].w += tmp;
			rest -= tmp;
			if (!rest) break;
		}
	}
	return flow - rest;
}

inline ll Dinic()
{
	ll ans = 0;
	while (Bfs()) ans += Dfs(s, 1e9);
	return ans;
}

inline void work()
{
	Clear(); ll num;
	read(n); t = n + 1;
	for (rei i = 1; i <= n; i++)
	{
		read(a[i]);
		if (a[i])
		{
			add_edge(i + n, t, 1);
			add_edge(t, i + n, 0);
		} 
	}
	for (rei i = 1; i <= n; i++)
	{
		read(num);
		if ((!num && a[i]) || !a[i])
		{
			add_edge(s, i, 1); 
			add_edge(i, s, 0);
			all++;
		} 
	}
	for (rei i = 1; i <= n; i++) for (rei j = 1; j <= n; j++)
	{
		read(num);
		if (num || i == j)
		{
			add_edge(i, j + n, 1);
			add_edge(j + n, i, 0);
		} 
	}
	if (Dinic() >= all)	printf("^_^\n");
	else printf("T_T\n");
}

int main()
{
	//freopen("a.txt", "r", stdin);
	read(T);
	while (T--) work();
	return 0;
}
2021/2/17 10:32
加载中...