口袋的天空
这个题实际上仍然是跑 Kruskal,只不过在达到 $k$ 个连通块时(即有 $n-k$ 条边时)我们就找到了最优解,此时直接输出即可。
时间复杂度 $O(m\log m)$。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
   | #include<iostream> #include<cstdio> #include<algorithm> #include<queue> #include<vector> #include<cstring> #define ll long long using namespace std;
  const ll M=1e4,N=1e3;
  ll n,m,k,ans,cnt;
  ll fa[N+5];
  struct node{ 	ll u,v,w; 	bool operator < (const node& rhs) const{ 		return w<rhs.w; 	} }edge[M+5];
  ll find(ll x) { 	if(fa[x]==x) return x; 	return fa[x]=find(fa[x]); }
  void uni(ll x,ll y) { 	fa[find(x)]=find(y); }
  void kruskal() { 	for(ll i=1;i<=m;i++) { 		if(find(edge[i].u)!=find(edge[i].v)) { 			ans+=edge[i].w;cnt++; 			uni(edge[i].u,edge[i].v); 			if(cnt>=n-k) return; 		} 	} }
  inline ll read() { 	ll ret=0,f=1;char ch=getchar(); 	while(ch<'0'||ch>'9') {if(ch=='-') f=-f;ch=getchar();} 	while(ch>='0'&&ch<='9') {ret=(ret<<3)+(ret<<1)+ch-'0';ch=getchar();} 	return ret*f; }
  void write(ll x) { 	static char buf[22];static ll len=-1; 	if(x>=0) { 		do{buf[++len]=x%10+48;x/=10;}while(x); 	} 	else { 		putchar('-'); 		do{buf[++len]=-(x%10)+48;x/=10;}while(x); 	} 	while(len>=0) putchar(buf[len--]); }
  int main() {
  	n=read();m=read();k=read();
  	for(ll i=1;i<=m;i++) { 		edge[i].u=read();edge[i].v=read();edge[i].w=read(); 	}
  	sort(edge+1,edge+m+1);
  	for(ll i=1;i<=n;i++) fa[i]=i;
  	kruskal();
  	if(cnt>=n-k) write(ans); 	else printf("No Answer");
  	return 0; }
   |