题目描述
给出一颗树,将这棵树分成若干个部分,每部分的节点数相同
求方案数
思路
将树分成a部分,每部分节点数为b
易得a*b=n,且这种分发是固定的
所以我们可以枚举n的约数i
然后判断是否可以分
详情见代码
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
struct wh_
{
int w, h;
}wh[5000250];
int h[1000250], size[1000250];
int n, x, y, t, Ans, sum;
inline int read()
{
int x = 0, r = 1; char c = getchar();
while(c < '0' || c > '9'){if(c == '-')r = -1;c = getchar();}
while('0' <= c && c <= '9')x = x * 10 + c - 48, c = getchar();
return x * r;
}
void hw(int x, int y)
{wh[++t] = (wh_){y, h[x]}, h[x] = t;}
void DFS(int now, int last)//求每个点的大小(包含自己共含有多少个点)
{
size[now] = 1;
for(int i = h[now]; i; i = wh[i].h)
if(wh[i].w != last)
{
DFS(wh[i].w, now);
size[now] += size[wh[i].w];
}
}
void init(int k)
{
sum = 0;
for(int i = 1; i <= n; ++i)
if(!(size[i] % k))sum++;
if(sum == n / k)Ans++;//树被分成sum块,若sum*k=n则此方案成立
}
int main()
{
n = read();
for(int i = 1; i < n; ++i)
{
x = read(), y = read();
hw(x, y),hw(y, x);
}
DFS(1, 0);//预处理
Ans = 1;
if(n > 1)Ans++;
for(int i = 2; i <= (int)sqrt(n); ++i)
if(!(n % i))//约数
{
init(i);
if(i * i != n)init(n / i);
}
printf("%d", Ans);
return 0;
}