C. Tree Permutation

Problem - C - Codeforces

C. Tree Permutation_第1张图片

C. Tree Permutation_第2张图片 思路:这是一个树排列问题,只要求出所有的排列对应的情况然后除以排列的种类就可以了,对于一个排列来说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
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include 
#include
#include
#define fi first
#define se second
#define i128 __int128
using namespace std;
typedef long long ll;
typedef double db;
typedef pair PII;
typedef pair > 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 T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template 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

你可能感兴趣的:(codeforces,算法)