一条路径可以往上走也可以往下走,所以一个点最多连出两条边。
考虑f[x]为x个点的树的最大答案,则f[x]<=f[x/3]+1,所以最大答案也是log3n级别的,大概在10个左右。
因此我们就可以树形dp了,f[x][j][0/1/2]表示以x为根的子树中不便利值均<=j,x向儿子连了0/1/2条边的方案数。
我们显然有转移:
f[x][j][0]=∏y(f[y][j−1][0]+f[y][j−1][1]+f[y][j−1][2])
f[x][j][1]=∑y0(f[y0][j][0]+f[y0][j][1])∏y!=y0(f[y][j−1][0]+f[y][j−1][1]+f[y][j−1][2])
f[x][j][2]=∑y0∑y1(f[y0][j][0]+f[y0][j][1])(f[y1][j][0]+f[y1][j][1])∏y!=y0∧y!=y1(f[y][j−1][0]+f[y][j−1][1]+f[y][j−1][2])
但是这个转移太慢了,我们考虑优化,一个儿子一个儿子的做,我们就得到了优化:令t1=f[y][j][0]+f[y][j][1],
t2=f[y][j-1][0]+f[y][j-1][1]+f[y][j-1][2].
那么有
f[x][j][2]=f[x][j][2]∗t2+f[x][j][1]∗t1
f[x][j][1]=f[x][j][1]∗t2+f[x][j][0]∗t1
f[x][j][0]=f[x][j][0]∗t2
复杂度 O(n∗10∗3)
还要注意一点的是如果根据答案是否为0来判断是否存在这种方案,需要把0和%p=0区别开来。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 100010
inline char gc(){
static char buf[1<<16],*S,*T;
if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
return *S++;
}
inline int read(){
int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
return x*f;
}
int n,m,mod,h[N],num=0,f[N][12][3];
//f[x][j][0/1/2],以x为根的子树中不便利值均<=j,x向儿子连了0/1/2条边的方案数
struct edge{
int to,next;
}data[N<<1];
inline int mo(ll x){
if(!x) return 0;x%=mod;return x?x:mod;
}
inline void dfs(int x,int j,int Fa){
f[x][j][0]=1;
for(int i=h[x];i;i=data[i].next){
int y=data[i].to;if(y==Fa) continue;
dfs(y,j,x);int t1=mo(f[y][j][0]+f[y][j][1]);
int t2=j?mo(f[y][j-1][0]+f[y][j-1][1]+f[y][j-1][2]):0;
f[x][j][2]=mo((ll)f[x][j][2]*t2+(ll)f[x][j][1]*t1);
f[x][j][1]=mo((ll)f[x][j][1]*t2+(ll)f[x][j][0]*t1);
f[x][j][0]=mo((ll)f[x][j][0]*t2);
}
}
int main(){
// freopen("a.in","r",stdin);
n=read();m=read();mod=read();
if(m!=n-1){puts("-1");puts("-1");return 0;}
for(int i=1;i<=m;++i){
int x=read(),y=read();
data[++num].to=y;data[num].next=h[x];h[x]=num;
data[++num].to=x;data[num].next=h[y];h[y]=num;
}for(int i=0;;++i){
dfs(1,i,0);int ans=f[1][i][0]+f[1][i][1]+f[1][i][2];
if(!ans) continue;
printf("%d\n%d\n",i,ans%mod);return 0;
}
}