【费用流】 HDOJ 5352 MZL's City

每个操作当成点,后面的操作费用低。。。建图跑费用流就行了。。。。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int maxn = 705;
const int maxm = 300005;
const int INF = 0x3f3f3f3f;

struct Edge
{
	int v, c, w, next;
	Edge () {}
	Edge(int v, int c, int w, int next) : v(v), c(c), w(w), next(next) {}
}E[maxm];

set<int> ss[maxn];
queue<int> q;
int H[maxn], cntE;
int visit[maxn];
int cap[maxn];
int vis[maxn];
int dis[maxn];
int cur[maxn];
int a[maxn];
int res[maxn];
int flow, cost, s, t, T;

void addedges(int u, int v, int c, int w)
{
	E[cntE] = Edge(v, c, w, H[u]);
	H[u] = cntE++;
	E[cntE] = Edge(u, 0, -w, H[v]);
	H[v] = cntE++;
}

bool spfa()
{
	memset(dis, INF, sizeof dis);
	cur[s] = -1;
	vis[s] = ++T;
	cap[s] = INF;
	dis[s] = 0;
	q.push(s);
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		vis[u] = T - 1;
		for(int e = H[u]; ~e; e = E[e].next) {
			int v = E[e].v, c = E[e].c, w = E[e].w;
			if(c && dis[v] > dis[u] + w) {
				dis[v] = dis[u] + w;
				cap[v] = min(cap[u], c);
				cur[v] = e;
				if(vis[v] != T) {
					vis[v] = T;
					q.push(v);
				}
			}
		}
	}
	if(dis[t] == INF) return false;
	cost += cap[t] * dis[t];
	flow += cap[t];
	for(int e = cur[t]; ~e; e = cur[E[e ^ 1].v]) {
		E[e].c -= cap[t];
		E[e ^ 1].c += cap[t];
	}
	return true;
}

int mfmc()
{
	flow = cost = 0;
	while(spfa());
	return cost;
}

void init()
{
	cntE = T = 0;
	memset(H, -1, sizeof H);
	memset(vis, 0, sizeof vis);
}

void dfs(int u, int id, int m)
{
	addedges(id, u + m, 1, 0);
	for(set<int>::iterator it = ss[u].begin(); it != ss[u].end(); it++) if(!visit[*it]) visit[*it] = true, dfs(*it, id, m);
}

void work()
{
	int n, m, m2, op, u, v, K;
	scanf("%d%d%d", &n, &m, &K);
	int cnt = 0;
	
	for(int i = 1; i <= n; i++) ss[i].clear();
	
	s = 0, t = m + n + 1;
	for(int i = 1; i <= n; i++) addedges(i + m, t, 1, 0);
	for(int i = 1; i <= m; i++) {
		scanf("%d", &op);
		if(op == 1) {
			scanf("%d", &u);
			a[cnt++] = cntE;
			addedges(s, i, K, m - i);
			memset(visit, 0, sizeof visit);
			visit[u] = true;
			dfs(u, i, m);
		}
		if(op == 2) {
			scanf("%d%d", &u, &v);
			ss[u].insert(v);
			ss[v].insert(u);
		}
		if(op == 3) {
			scanf("%d", &m2);
			for(int j = 1; j <= m2; j++) {
				scanf("%d%d", &u, &v);
				ss[u].erase(v);
				ss[v].erase(u);
			}
		}
	}

	int ans = 0;
	mfmc();
	for(int i = 0; i < cnt; i++) res[i] = E[a[i] ^ 1].c, ans += res[i];
	
	printf("%d\n", ans);
	for(int i = 0; i < cnt; i++) printf("%d%c", res[i], i == cnt - 1 ? '\n' : ' ');
}

int main()
{
	int _;
	scanf("%d", &_);
	while(_--) {
		init();
		work();
	}
	
	return 0;
}


你可能感兴趣的:(网络流)