[BZOJ1433][luogu_P2055][ZJOI2009]假期的宿舍

[BZOJ1433][luogu_P2055][ZJOI2009]假期的宿舍

试题描述

QAQ

输入

TAT

输出

Q_T

输入示例

1
3
1 1 0
0 1 0
0 1 1
1 0 0
1 0 0

输出示例

^_^

数据规模及约定

对于 \(30\texttt{%}\) 的数据满足 \(1 \le n \le 12\)

对于 \(100\texttt{%}\) 的数据满足 \(1 \le n \le 50,1 \le T \le 20\)

题解

每个人和每个人的床分别建一个节点,源点向不回家的和不是学生的人连边,是学生的床向汇点连边,每个人向他认识人的床连边,以上所有边容量都为 \(1\),跑最大流看是否满。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
#define rep(i, s, t) for(int i = (s); i <= (t); i++)
#define dwn(i, s, t) for(int i = (s); i >= (t); i--)

int read() {
	int x = 0, f = 1; char c = getchar();
	while(!isdigit(c)){ if(c == '-') f = -1; c = getchar(); }
	while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); }
	return x * f;
}

#define maxn 110
#define maxm 5210
#define oo 2147483647

struct Edge {
	int from, to, flow;
	Edge() {}
	Edge(int _1, int _2, int _3): from(_1), to(_2), flow(_3) {}
};
struct Dinic {
	int n, m, s, t, head[maxn], nxt[maxm];
	Edge es[maxm];
	int vis[maxn], Q[maxn], hd, tl;
	int cur[maxn];
	
	void init() {
		m = 0; memset(head, -1, sizeof(head));
		return ;
	}
	void setn(int _) {
		n = _;
		return ;
	}
	
	void AddEdge(int a, int b, int c) {
		es[m] = Edge(a, b, c); nxt[m] = head[a]; head[a] = m++;
		es[m] = Edge(b, a, 0); nxt[m] = head[b]; head[b] = m++;
		return ;
	}
	
	bool BFS() {
		memset(vis, 0, sizeof(vis));
		vis[t] = 1;
		hd = tl = 0; Q[++tl] = t;
		while(hd < tl) {
			int u = Q[++hd];
			for(int i = head[u]; i != -1; i = nxt[i]) {
				Edge& e = es[i^1];
				if(!vis[e.from] && e.flow) {
					vis[e.from] = vis[u] + 1;
					Q[++tl] = e.from;
				}
			}
		}
		return vis[s] > 0;
	}
	
	int DFS(int u, int a) {
		if(u == t || !a) return a;
		int flow = 0, f;
		for(int& i = cur[u]; i != -1; i = nxt[i]) {
			Edge& e = es[i];
			if(vis[e.to] == vis[u] - 1 && (f = DFS(e.to, min(a, e.flow)))) {
				flow += f; a -= f;
				e.flow -= f; es[i^1].flow += f;
				if(!a) return flow;
			}
		}
		return flow;
	}
	
	int MaxFlow(int _s, int _t) {
		s = _s; t = _t;
		int flow = 0;
		while(BFS()) {
			rep(i, 1, n) cur[i] = head[i];
			flow += DFS(s, oo);
		}
		return flow;
	}
} sol;

bool stu[maxn];

int main() {
	int T = read();
	while(T--) {
		int n = read(), S = (n << 1) + 1, T = S + 1;
		sol.init(); sol.setn((n << 1) + 2);
		int cnt = 0;
		rep(i, 1, n){ stu[i] = read(); if(stu[i]) sol.AddEdge(i + n, T, 1); }
		rep(i, 1, n) if(!read() || !stu[i]) sol.AddEdge(S, i, 1), cnt++;
		rep(i, 1, n) rep(j, 1, n) if(read() || i == j) sol.AddEdge(i, j + n, 1);
		puts(sol.MaxFlow(S, T) == cnt ? "^_^" : "T_T");
	}
	
	return 0;
}
posted @ 2017-11-28 19:58  xjr01  阅读(100)  评论(0编辑  收藏