填坑(p.358)
以前天真的以为用prim把n-1条边求出来就可以
现在看来是我想多了
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream> const int N = + ; struct Node {
int x, y;
Node(int x = , int y = ) : x(x), y(y) {}
}p[N]; int sqr(int x) {
return x * x;
} int dist(const Node& a, const Node& b) {
return sqr(a.x - b.x) + sqr(a.y - b.y);
} struct Edge {
int u, v, w;
Edge() {}
Edge(int u, int v, int w) : u(u), v(v), w(w) {}
bool operator < (const Edge& rhs) const {
return w < rhs.w;
}
};
#include<vector>
std::vector<Edge> edges, pree; int n, ans;
int d[N], pre[N], dis[N][N];
bool inMST[N]; void prim() {
memset(d, 0x3f, sizeof d);
memset(inMST, , sizeof inMST);
ans = d[] = ;
for(int i = ; i < n; i++) {
int u = -;
for(int v = ; v < n; v++) if(!inMST[v]) {
if(u == - || d[v] < d[u]) u = v;
}
inMST[u] = ;
ans += d[u];
if(i) edges.push_back(Edge(u, pre[u], dis[u][pre[u]]));
for(int v = ; v < n; v++) if(!inMST[v]) {
if(d[v] > d[u] + dis[u][v]) {
d[v] = d[u] + dis[u][v];
pre[v] = u;
}
}
}
} int fa[N];
int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
} bool merge(int x, int y) {
x = find(x), y = find(y);
if(x == y) return ;
return fa[x] = y, ;
} void UFS_init() {
for(int i = ; i < n; i++) fa[i] = i;
} void pre_kruskal() {
for(int i = ; i < n; i++) {
for(int j = i + ; j < n; j++) {
pree.push_back(Edge(i, j, dis[i][j]));
}
}
sort(pree.begin(), pree.end()); UFS_init();
int MST = n;
ans = ;
for(unsigned i = ; i < pree.size(); i++) {
const Edge& e = pree[i];
if(merge(e.u, e.v)) {
edges.push_back(e);
ans += e.w;
if(--MST == ) break;
}
}
} int q;
#include<vector>
std::vector<int> frees[];
int cost[];
#include<cassert>
void Kruskal(int mask) {
UFS_init();
int MST = n, res = ;
for(int j = ; j < q; j++) if(mask >> j & ) {
res += cost[j];
for(unsigned i = ; i < frees[j].size(); i++) {
MST -= merge(frees[j][i-], frees[j][i]);
}
} for(unsigned i = ; i < edges.size(); i++) {
if(MST == ) break;
if(merge(edges[i].u, edges[i].v)) res += edges[i].w, MST--;
}
assert(MST == );
ans = std::min(ans, res);
} int main() {
#ifdef DEBUG
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif int T; scanf("%d", &T);
while(T--) {
pree.clear();
edges.clear();
scanf("%d%d", &n, &q);
for(int i = ; i < q; i++) {
int m;
scanf("%d%d", &m, cost + i);
frees[i].resize(m);
for(int j = ; j < m; j++) {
scanf("%d", &frees[i][j]);
--frees[i][j];
}
}
for(int i = ; i < n; i++) {
scanf("%d%d", &p[i].x, &p[i].y);
for(int j = ; j < i; j++) {
dis[i][j] = dis[j][i] = dist(p[i], p[j]);
}
}
pre_kruskal();
std::sort(edges.begin(), edges.end());
for(int mask = ; mask < ( << q); mask++) {
Kruskal(mask);
} printf("%d\n", ans);
if(T) puts("");
} return ;
}