C. Tree Permutation

该文章详细解析了Codeforces上题号为C的TreePermutation问题。作者使用深度优先搜索(DFS)策略,计算树的所有排列并求解平均边数。通过计算每条边在所有排列中出现的次数,最终得出边的平均数量。算法涉及到排列的计算以及树的遍历。
摘要由CSDN通过智能技术生成

Problem - C - Codeforces

 思路:这是一个树排列问题,只要求出所有的排列对应的情况然后除以排列的种类就可以了,对于一个排列来说n!来说,因为每个数的地位都是相等的,每条边的地位也是相等的(相邻的两个数为一条边),那么每条边出现的次数就是相同的,一共会有n*(n-1)种边,一共有n!*(n-1)条边,那么每种边有(n!*(n-1))/(n*(n-1))=(n-1)!条,那么我们可以先算出来所有种的边的和,然后乘以(n-1)!就能够得到所有边的和,因为题中求均值,那么需要除以排列的种类,一共有n!种,那么化简之后最后的答案就是所有种的边的和/n ,而对于这种情况,我们可以用dfs来枚举每条边,u,j我们看一下以j为根节点的子树有多少个点,假如说有sum个,那么其他的点有n-sum个,那么经过这条边的路径有(sum)*(n-sum)*2个(因为有a->b,b->a两种情况),所以我们只需要枚举每条边让和除以n,然后相加得到答案

// Problem: C. Tree Permutation
// Contest: Codeforces - 2023 ICPC HIAST Collegiate Programming Contest
// URL: https://codeforces.com/gym/104493/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms

#include<iostream>
#include<cstring>
#include<string>
#include<sstream>
#include<bitset>
#include<deque>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<vector> 
#include<set>
#include<cstdlib>
#define fi first
#define se second
#define i128 __int128
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
typedef pair<int,pair<int,int> > PIII;
const double eps=1e-7;
const int N=5e5+7 ,M=5e5+7, INF=0x3f3f3f3f,mod=1e9+7,mod1=998244353;
const long long int llINF=0x3f3f3f3f3f3f3f3f;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
inline void write(ll x) {if(x < 0) {putchar('-'); x = -x;}if(x >= 10) write(x / 10);putchar(x % 10 + '0');}
inline void write(ll x,char ch) {write(x);putchar(ch);}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
bool cmp0(int a,int b) {return a>b;}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
void hack() {printf("\n----------------------------------\n");}

int T,hackT;
int n,m,k;
int h[N],e[M],ne[M],idx;
int sum[N];
double ans;

void add(int a,int b) {
	e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

void dfs(int u,int fa) {
	sum[u]=1;
	for(int i=h[u];i!=-1;i=ne[i]) {
		int j=e[i];
		
		if(j==fa) continue;
		dfs(j,u);
		sum[u]+=sum[j];
		ans+=(db)sum[j]*(n-sum[j])*2/n;
	}
}

void solve() {
	n=read();
	
	memset(h,-1,sizeof(int)*(n+4));
	idx=0;
	ans=0;
	for(int i=1;i<n;i++) {
		int a=read(),b=read();
		add(a,b),add(b,a);
	}
	
	dfs(1,-1);
	
	printf("%.14f\n",ans);
}   

int main() {
    // init();
    // stin();

    scanf("%d",&T);
    // T=1; 
    while(T--) hackT++,solve();
    
    return 0;       
}          

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值