Test instructions
N Cities, M-bars. In addition, each city can also build a pier.
If there are docks in two cities, these two cities can reach each other.
To find the minimum spanning tree.
Ideas:
For the pier, you can connect all the terminals to a 0 point, at the cost of building a pier.
At this time run two times, again there is a pier situation, the second time there is no pier.
In this case, the question is whether the road will be connected without a pier.
Then also note that negative roads must be connected, so the cost is even smaller!
Code:
#include "stdio.h" #include "algorithm" #include "string.h" #include "iostream" #include "queue" #include "map" #include " String "#define MoD 1000000007using namespace std;struct node{int x,y,s;} edge[123456];int pre[12345];int cmp (node A,no De b) {return A.S<B.S;} int finde (int x) {return X!=pre[x]?pre[x]=finde (Pre[x]): x;} int main () {int n,m; while (scanf ("%d%d", &n,&m)!=-1) {for (int i=0; i<=n; i++) pre[i]=i; for (int i=0; i<m; i++) scanf ("%d%d%d", &EDGE[I].X,&EDGE[I].Y,&EDGE[I].S); for (int i=m; i<n+m; i++) {edge[i].x=0; edge[i].y=i-m+1; scanf ("%d", &EDGE[I].S); if (edge[i].s==-1) edge[i].s=-19999; } sort (edge,edge+n+m,cmp); int ans=0,ans2=0; for (int i=0; i<n+m; i++) {if (edge[i].s==-19999) continue; int F1=finde (edge[i].x); int F2=finde (EDGE[I].Y); if (F1!=F2) {ans+=edge[i].S; PRE[F1]=F2; } else if (edge[i].s<0) Ans+=edge[i].s; } for (int i=0; i<=n; i++) pre[i]=i; for (int i=0; i<n+m; i++) {if (edge[i].x==0) continue; int F1=finde (edge[i].x); int F2=finde (EDGE[I].Y); if (F1!=F2) {ans2+=edge[i].s; PRE[F1]=F2; } else if (edge[i].s<0) Ans2+=edge[i].s; } int sum=0; for (int i=1;i<=n;i++) if (pre[i]==i) sum++; if (sum!=1) printf ("%d\n", ans); else printf ("%d\n", Min (ans,ans2)); } return 0;}
[minimum spanning tree] Blue Bridge Cup city construction