跳到正文

题解

CF1857G 题解

szm2023约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年4月9日
更新
2026年4月9日
篇幅
约 2 分钟

版本

  1. v1当前

CF1857G 题解

加入的图边不在最小生成树里。考虑做最小生成树的过程,边权从小到大排序,如果这条边连接的两个连通块之前已经联通,等价于它连接的两个连通块可以用更小的方式连接。

具体地,我们先把树边从小到大排序。假设这条边连接了连通块 pp 和 qq,则还有 szp×szq−1sz_{p} \times sz_{q} - 1 条连接的方式,也就是可以作为图边。每条边的边权有 S−w+1S - w + 1 种(ww 是当前树边边权,+1是因为可以不选)。

Code
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod=998244353;
const int maxn=2e5+5;
int fa[maxn],sz[maxn];
int t,n,s,ans,cnt,tot;
struct node{
	int u,v,w;
	bool operator<(const node &x)const{
		return w<x.w;
	}
}e[maxn];
int get_fa(int x){
	return fa[x]==x?x:fa[x]=get_fa(fa[x]);
}
int qpow(int a,int b){
	int res=1;
	while(b){
		if(b&1) res=res*a%mod;
		a=a*a%mod;
		b>>=1;
	}
	return res%mod;
}
signed main(){
	cin>>t;
	while(t--){
		cin>>n>>s;
		ans=1,cnt=0,tot=n*(n-1)/2;
		for(int i=1;i<=n;i++){
			e[i]={0,0,0};
			fa[i]=i;
			sz[i]=1;
		}
		for(int i=1;i<n;i++){
			int u,v,w;
			cin>>u>>v>>w;
			e[i]={u,v,w};
		}
		sort(e+1,e+n);
		for(int i=1;i<n;i++){
			int u=e[i].u,v=e[i].v,w=e[i].w;
			int p=get_fa(u),q=get_fa(v);
			if(sz[p]!=1||sz[q]!=1)
				ans=ans*qpow(s-w+1,sz[p]*sz[q]-1)%mod;
			//cout<<sz[p]<<" "<<sz[q]<<endl;
			sz[p]+=sz[q];
			fa[q]=p;
		}
		cout<<ans<<endl;
	}
	return 0;
}
原文