is actually a problem of the smallest spanning tree. We only need to exclude the bad points, then make a minimal spanning tree for the other points, and then connect the bad points to the spanning tree (the least expensive point each time). Of course, if not all of the points are connected together, it is impossible.
There is also a situation that requires a special sentence, that is, if there are only two points, and all are bad, this is also legal.
The code is as follows:
#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <vector>using namespace STD;#define MAXN 210000#define LL Long Long#define INF 0x3f3f3f3f vector<int>G[MAXN],W[MAXN];typedef struct{intX,y,w;} P P P[MAXN];intCMP (P p1,p p2) {returnP1.W<P2.W;}intE,FA[MAXN];intA[MAXN],FLAG[MAXN];intFind (intx) {returnFa[x]==x?x:find (Fa[x]);}/// If there are only two points, and all of them are bad, they must be sentenced .intMain () {intN,m,k;//Freopen ("In.txt", "R", stdin); while(scanf("%d%d%d", &n,&m,&k)!=eof) {intHmemset(Flag,0,sizeof(flag)); for(intI=1; i<=n;i++) fa[i]=i; for(intI=1; i<=n;i++) G[i].clear (), w[i].clear (); for(intI=0; i<k;i++) {scanf("%d", &a[i]); flag[a[i]]=1; } e=0; for(intI=1; i<=m;i++) {intX, Y, Zscanf("%d%d%d", &x,&y,&z);if(k==2&&x==a[0]&&y==a[1]) H=z;if(k==2&&y==a[0]&&x==a[1]) H=z; P[e].x=x; P[e].y=y; P[e].w=z; e++; P[e].x=y; P[e].y=x; P[e].w=z; e++; G[x].push_back (y); W[x].push_back (z); G[y].push_back (x); W[y].push_back (z); }if(n==2&&k==2) {printf("%d\n", h);Continue; } sort (p,p+e,cmp);intCnt=1;BOOLdl{true; ll ans=0; for(intI=0; i<e;i++) {intX=P[I].X,Y=P[I].Y;if(!flag[x]&&!flag[y]) {intXx=find (x);intYy=find (y);if(XX!=YY) {ans+=p[i].w; cnt++; Fa[xx]=yy; } } }if(cnt<n-k) bl=false;intsum1=0, sum2=0; for(intI=0; i<k;i++) {intX=a[i],y,tmp=inf; for(intj=0; J<g[x].size (); j + +) {Y=g[x][j];if(Flag[y])Continue;if(Tmp>w[x][j]) tmp=w[x][j]; }if(Tmp<inf) ans+=tmp,cnt++; }if(cnt<n) bl=false;if(!BL)printf("impossible\n");Else printf("%lld\n", ans); }return 0;}
csuoj--1633 Landline Telephone Network