链接
题目描述
一棵树删去任意条边,可以得到若干棵新树。
若使让每棵新树的节点数相同。问有多少种方法分割这棵树。
思路
来自大佬
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
struct node
{
int to, next;
}g[2000006];
int n, t, num, sum, ans;
int y[1000006], h[1000006], size[1000006];
int read()
{
int x = 0, flag = 1; char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') flag = -1; ch = getchar();}
while (ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar();}
return x * flag;
}
void add(int x, int y)
{
g[++t] = (node){y, h[x]}; h[x] = t;
g[++t] = (node){x, h[y]}; h[y] = t;
}
void dfs(int x, int fath)
{
size[x] = 1;
for(int i = h[x]; i; i = g[i].next)
{
int to = g[i].to;
if(to == fath) continue;
dfs(to, x);
size[x] += size[to];
}
}
int main()
{
n = read();
for(int i = 1; i < n; ++i)
{
int x, y;
x = read(); y = read();
add(x, y);
}
dfs(1, 0);
for(int i = 1; i <= floor(sqrt(n)); ++i)
{
if(i * i == n) y[++num] = i;
else if(n % i == 0) {
y[++num] = i;
y[++num] = n / i;
}
}
for(int i = 1; i <= num; ++i) {
for(int j = 1; j <= n; ++j)
if(size[j] % y[i] == 0) sum++;
if(sum == n / y[i]) ans++;
sum = 0;
}
printf("%d", ans);
return 0;
}