BZOJ4006【斯坦纳树】

/* I will wait for you */

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <string>
#define make(a,b) make_pair(a,b)
#define fi first
#define se second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef map<int, int> mii;

const int maxn = 1200;
const int maxm = 1010;
const int maxs = 26;
const int inf = 0x3c3c3c3c;
const int P = 1000000007;
const double error = 1e-9;

inline ll read()
{
	ll x = 0, f = 1; char ch = getchar();
	while (ch > '9' || ch < '0' )
		f = (ch == '-' ? -1 : 1), ch = getchar();
	while (ch <= '9' && ch >= '0')
		x = x * 10 + ch - '0', ch = getchar();
	return f * x;
}

struct edge
{
	int v, w, next;
} e[maxn * 10];

struct query
{
	int pos, color;
} t[maxn];

int n, m, p, cnt, head[maxn], bin[maxn], s[maxn], sum[maxn], 
    tot[maxn], dp[maxn], f[maxn][maxn], vis[maxn][maxn];

queue<pii> q;

void insert(int u, int v, int w)
{
	e[cnt] = (edge) {v, w, head[u]}, head[u] = cnt++;
	e[cnt] = (edge) {u, w, head[v]}, head[v] = cnt++;
}

int checker(int x)
{
	memset(sum, 0, sizeof sum);

	for (int i = 0; i < p; i++)
		if (x & bin[i])
			sum[t[i].color]++;

	for (int i = 0; i < p; i++)
		if (sum[i] != 0 && sum[i] != tot[i])
			return 0;

	return 1;
}

void spfa()
{
	while (!q.empty()) {
		pii u = q.front(); q.pop();
		vis[u.fi][u.se] = 0;

		for (int i = head[u.fi]; i != -1; i = e[i].next) {
			int v = e[i].v;

			if (f[u.fi][u.se] + e[i].w < f[v][u.se | s[v]]) {
				f[v][u.se | s[v]] = f[u.fi][u.se] + e[i].w;
				if ((u.se | s[v]) == u.se && !vis[v][u.se]) {
					vis[v][u.se] = 1;
					q.push(make(v, u.se));
				}
			}
		}
	}
}

void init()
{
	for (int i = 0; i <= 20; i++)
		bin[i] = 1 << i;

	memset(f, 0x3c, sizeof f);
	memset(dp, 0x3c, sizeof dp);
	memset(head, -1, sizeof head);
}

int main()
{
	n = read(), m = read(), p = read(), init();

	for (int i = 1; i <= m; i++) {
		int u = read(), v = read(), w = read();
		insert(u, v, w);
	}

	for (int i = 0; i < p; i++) {
		t[i].color = read(), t[i].pos = read();
		f[t[i].pos][bin[i]] = 0;
		s[t[i].pos] = bin[i];
		tot[t[i].color]++;
	}


	for (int x = 0; x < bin[p]; x++) {
		for (int i = 1; i <= n; i++) {
			for (int j = (x - 1) & x; j; j = (j - 1) & x)
		f[i][x] = min(f[i][x], f[i][j | s[i]] + f[i][(x ^ j) | s[i]]);
			if (f[i][x] != inf)
			       q.push(make(i, x)), vis[i][x] = 1;
		}
		spfa();
	}

	for (int x = 0; x < bin[p]; x++)
		for (int i = 1; i <= n; i++)
			dp[x] = min(dp[x], f[i][x]);

	for (int x = 0; x < bin[p]; x++)
		if (checker(x))
			for (int j = (x - 1) & x; j; j = (j - 1) & x)
				if(checker(j))
			dp[x] = min(dp[x], dp[j] + dp[x ^ j]);

	printf("%d\n", dp[bin[p] - 1]);

	return 0;
}

你可能感兴趣的:(BZOJ4006【斯坦纳树】)