题目链接:http://acm.hust.edu.cn/vjudge/problem/36013
题目大意:给你n个点,你的任务是让这n个点连通。为此,你有两种方法,1、在某两点之间建边,费用为两点之间欧几里得距离的平方。2、购买一些套餐,当买了某个套餐后,套餐中的这些点将变得相互连通,问完成任务的最小费用是多少。
思路:若直接枚举套餐,再求最小生成树,肯定会超时。所以,按刘汝佳说的那样,先求一遍不买任何套餐的最小生成树,然后再枚举套餐,并只考虑最小生成树的边和套餐的边,对这些边再求最小生成树即可。为什么可以这样呢,我们想,我们第一次求的那些边,肯定都是最优的,那些边恰好构成一棵最小生成树,不会再有比它小的了,购买套餐之后,结果就是,不仅以前求出的最优边还在里面,还会加入一些更优的边(权值为0),因此这些边肯定会有一棵不比原来差的生成树。换句话说,我要选边,肯定就是,从套餐中的边和另外一些最优的边中选,这个另外一些,肯定存在于第一次不买任何套餐所求得的最小生成树中,其他的都不予考虑。
#include<cstdio>
#include<cstring>
#include<vector>
#include<iostream>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 1000 + 10;
struct Edge
{
int to,from,value;
Edge(int to = 0, int from = 0, int value = 0) : to(to),from(from),value(value){}
bool operator < (const Edge& b) const {
return value < b.value;
}
};
int n, q, cost[10];
int x[maxn], y[maxn], pre[maxn];
vector<int> food[10];
vector<Edge> edge;
int find(int x)
{
return pre[x] == x ? x : pre[x] = find(pre[x]);
}
int MST(int cnt, vector<Edge>& e, vector<Edge>& used)
{
int ans = 0;
used.clear();
for (int i = 0; i < e.size(); i++) {
int x = find(e[i].to), y = find(e[i].from);
if (x != y) {
pre[x] = y;
cnt++;
ans += e[i].value;
used.push_back(e[i]);
}
if (cnt == n-1) return ans;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--) {
edge.clear();
scanf("%d%d",&n,&q);
for (int i = 0; i < q; i++) {
food[i].clear();
int len;
scanf("%d%d",&len,&cost[i]);
while(len--) {
int x;
scanf("%d",&x);
food[i].push_back(x-1);
}
}
for (int i = 0; i < n; i++)
scanf("%d%d",&x[i],&y[i]);
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
int v = (x[j]-x[i])*(x[j]-x[i]) + (y[j]-y[i])*(y[j]-y[i]);
edge.push_back(Edge(i, j, v));
}
}
for (int i = 0; i < n; i++) pre[i] = i;
vector<Edge> Need;
sort(edge.begin(), edge.end());
int ans = MST(0, edge, Need);
for (int i = 1; i < (1<<q); i++) {
int cnt = 0, c = 0;
for (int j = 0; j < n; j++) pre[j] = j;
for (int j = 0; j < q; j++) if((1<<j)&i) {
c += cost[j];
for (int ii = 0; ii < food[j].size(); ii++) {
for (int jj = ii+1; jj < food[j].size(); jj++) {
int x = find(pre[food[j][ii]]), y = find(pre[food[j][jj]]);
if (x != y) {
pre[y] = x;
cnt++;
}
}
}
}
vector<Edge> Nothing;
ans = min(ans, c + MST(cnt, Need, Nothing));
}
printf("%d\n",ans);
if (T) printf("\n");
}
}