Test instructions: Given n points, your task is to make them all connected. You can create some new side, the cost equals two points distance squared (of course the smaller the better), there are several "package", you can buy, you buy, then some side can connect up,
Each "package" is also spent, which allows you to find the minimum cost.
Analysis: The first thought is to consider all the circumstances of the calculation, and then find the least, first Count no "package", and then some, with binary enumeration words, the total time complexity is O (2QN2+N2LOGN), this time complexity is too big bar, will definitely time out,
Then we can optimize, first of all to calculate the minimum spanning tree, and each side is saved, then add the "package" after the enumeration is not all, this is an optimization, and then buy "package", then some weights become 0,
Do not add this, and then re-enumerate, we will connect them before the OK. The other is the same as the minimum spanning tree.
The code is as follows:
#include <cstdio> #include <iostream> #include <algorithm>using namespace Std;const int MAXN = 1000 + 10; struct node{int U, V, W; BOOL operator < (const node &p) Const {return W < P.W; }};node A[maxn*maxn/2];int P[MAXN], X[MAXN], Y[MAXN], N, M, Q[8][MAXN], c[2][10], indx, l[maxn];int Find (int x) {return x = = P[x]? X:P[X] = Find (P[x]);} int Kruskal () {//min spanning tree int ans = 0; L[0] = 0; for (int i = 0; i < indx; ++i) {int x = Find (A[I].U); int y = Find (A[I].V); if (x! = y) {ans + = A[I].W; P[x] = y; L[++l[0]] = i;//Save the edges of the smallest spanning tree}} return ans; int Kruskal2 () {//buy "package" after the minimum spanning tree int ans = 0; for (int i = 1; I <= l[0]; ++i) {int II = l[i]; int x = Find (A[II].U); int y = Find (A[II].V); if (x! = y) {p[x] = y; Ans + = A[II].W; }} return ans; int main () {//Freopen ("Int.txt", "R", stdin); int T; CIN >&Gt T while (t--) {scanf ("%d%d", &n, &m); for (int i = 0; i < m; ++i) {scanf ("%d%d", &c[0][i], &c[1][i]); for (int j = 0; J < C[0][i]; ++j) scanf ("%d", &q[i][j]); } for (int i = 0; i < n; ++i) scanf ("%d%d", &x[i], &y[i]); indx = 0; for (int i = 0; i < n; ++i)//Compute Right Plant for (int j = i+1; j < n; ++j) {a[indx].u = i+1; A[INDX].V = j+1; A[INDX++].W = (X[i]-x[j]) * (X[i]-x[j]) + (Y[i]-y[j]) * (Y[i]-y[j]); } sort (A, a+indx); for (int i = 0; I <= N; ++i) p[i] = i; int ans = Kruskal ();//Calculate the minimum charge for "package" for (int i = 0; i < (1<<m); ++i) {//binary enumeration int cost = 0; for (int j = 0; J <= N; ++j) p[j] = j; for (int j = 0, J < m; ++j) {if (i& (1<<j)) {cost + = C[1][j]; for (int k= 0; K < c[0][j]-1; ++k) {int xx = Find (q[j][k]); int yy = Find (q[j][k+1]); if (xx! = yy) p[xx] = yy; }}} ans = min (ans, cost + Kruskal2 ());//plus buy package fee, update minimum} printf ("%d\n ", ans); if (T) printf ("\ n"); } return 0;}
UVa 1151 Buy or build (minimum spanning tree + binary method brute force solution)