poj 3680(網絡流)

題目鏈接:http://poj.org/problem?id=3680

經典的區間k覆蓋模型, 費用流求解。


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <map>

using namespace std;

typedef int LL;

const LL INF = 1000000000;
const int N = 415;	
const int M = 2005 << 4;

struct Cost_Flow {
	
	struct Edge {
		LL cap, flow, cost;
		int v;
		Edge* next, * pair;

		inline void init(int v, LL c, LL p, Edge* e, Edge* e2) {
			this->v = v, cap = c, flow = 0, cost = p;
			next = e, pair = e2;
		}
	};

	Edge E[M], * it, * head[N], * path[N];
	int n, s, t;
	LL minCost, maxFlow;
	bool inq[N];
       	LL dis[N];
	queue<int> Q;

	void init(int n, int s, int t) {
		this->n = n, this->s = s, this->t = t;
		it = E;
		for (int i = 0; i < n; i++) {
			head[i] = 0;
		}
	}

	inline void add(int u, int v, LL c, LL p) {
		it->init(v, c, p, head[u], it + 1);
	      	head[u] = it++;
		it->init(u, 0, -p, head[v], it - 1);	
		head[v] = it++;
	}

	bool spfa() {
		LL tmp;
		for (int i = 0; i < n; dis[i++] = INF);
		Q.push(s); dis[s] = 0;
		path[s] = path[t] = 0;
		while (!Q.empty()) {
			int u = Q.front(); Q.pop(); inq[u] = 0;
			for (Edge* e = head[u]; e; e = e->next) {
				int v = e->v;
				if (e->cap > e->flow && dis[v] > (tmp = dis[u] + e->cost) ){
					dis[v] = tmp;
					path[v] = e->pair;
					if(inq[v]) continue;
					inq[v] = 1; Q.push(v);
				}
			}
		}
		return path[t];
	}

	void run() {
		maxFlow = minCost = 0;
		while(spfa()) {
			LL tmp = INF;
			for (Edge* e = path[t]; e; e = path[e->v])
				tmp = min(tmp, e->pair->cap - e->pair->flow);
			for (Edge* e = path[t]; e; e = path[e->v])
				e->pair->flow += tmp, e->flow -= tmp;
			minCost += tmp * dis[t];
			maxFlow += tmp;
		}
	}
}G;


int st[N], ed[N], W[N];
int tmp[N * 2];
map<int, int> Map;

int main() {
	int n, k, a, b, w, m, test;
	scanf("%d", &test);
	while (test--) {
		scanf("%d%d", &m, &k);
		int c = 0;
		for (int i = 0; i < m; i++) {
			scanf("%d%d%d", &a, &b, &w);
			tmp[c++] = a;
			tmp[c++] = b;
			st[i] = a, ed[i] = b, W[i] = w;	
		}

		sort(tmp, tmp + c);
 		c = unique(tmp, tmp + c) - tmp;
		Map.clear();
		for (int i = 0; i < c; i++) {
			Map[tmp[i]] = i + 1;
		}

		n = c + 2;

		G.init(n, 0, n - 1);		

		for (int i = 0; i < m; i++) {
			int u = Map[st[i]];
			int v = Map[ed[i]];
			G.add(u, v, 1, -W[i]);
		}

		for (int i = 1; i <= n - 1; i++)
			G.add(i - 1, i, k, 0);

		G.run();

		printf("%d\n", -G.minCost);
	}	
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章