Codeforces790B. Bear and Tree Jumps 【树型DP】

传送门


ans=ceiling(disi,jk)
f(x,k)=kx%k
ans=disi,j+f(disi,j,k)k=1k(disi,j+f(disi,j,k))

disi,jf(disi,j,k)


sz[i]=i,far[i]i
far[i],idisi,j=sz[i](nsz[i])
disi,j=sz[i](nsz[i])


d[u][i]=u,%k=i
vu,udept
d[u][i]=i,%k=i(v)
dis=(i+j2dept)%kd[u][i]d[v][j]
kdisf(dis,k),f(disa,b,k)(kdis)d[u][i]d[v][j]

#include
#include

using namespace std;

#define ll long long
#define MEM(a,x) memset(a,x,sizeof(a))

const int N = 2e5+5;

vector<int>G[N];
int sz[N],d[N][10];
ll ans;
int n,k;

inline int mod(int x){
    return (x%k+k)%k;
}

void init(int n){
    for(int i=0;i<=n;++i){
        G[i].clear();
        sz[i]=0;
        MEM(d[i],0);
    }
    ans=0;
}

void dfs(int u,int far,int dept){
    sz[u]=d[u][dept%k]=1;
    for(int v:G[u]){
        if(v==far){
            continue;
        }
        dfs(v,u,dept+1);
        for(int i=0;ifor(int j=0;jint dis=mod(i+j-2*dept);
                ans+=(ll)mod(k-dis)*d[u][i]*d[v][j];
            }
        }
        sz[u]+=sz[v];
        for(int i=0;iint main()
{
    //freopen("/home/yang/Desktop/r.txt","r",stdin);
    while(~scanf("%d%d",&n,&k)){
        init(n);
        for(int i=0;i1;++i){
            int u,v;
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
            G[v].push_back(u);
        }
        dfs(1,-1,0);
        printf("%lld\n",ans/k);
    }
    return 0;
}

你可能感兴趣的:(codeforces,树形DP)