点分治学习笔记

· · 个人记录

适合处理大规模的树上路径信息问题。

#include <bits/stdc++.h>
using namespace std;

inline int read()
{
    int x=0; int f=1; char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}

const int MAXN = 50005;
struct Node {int to,val;};
std::vector<Node> G[MAXN];
int vis[20005],f[20005],d[20005];
int last[20005],son[20005],t[5];
int n,cnt,ans,root,sum;

inline int gcd(int a,int b)
{return b ? gcd(b,a%b) : a;}

inline void addedge(int u,int v,int w)
{
    G[u].push_back((Node) {v,w});
    G[v].push_back((Node) {u,w});
}

void getroot(int x,int fa)
{
    son[x]=1; f[x]=0;
    int sz=G[x].size();
    for (int i = 0; i < sz; ++i)
    {
        int y=G[x][i].to;
        if(!vis[y] && y!=fa)
        {
            getroot(y,x); son[x]+=son[y];
            f[x]=max(f[x],son[y]);
        }
    }
    f[x]=max(f[x],sum-son[x]);
    if(f[x]<f[root]) root=x;
}

void getdeep(int x,int fa)
{
    int sz=G[x].size(); t[d[x]]++;
    for (int i = 0; i < sz; ++i)
    {
        int y=G[x][i].to;
        if(!vis[y]&&y!=fa)
        {
            d[y]=(d[x]+G[x][i].val)%3;
            getdeep(y,x);
        }
    }
}

inline int cal(int x,int now)
{
    t[0]=t[1]=t[2]=0;
    d[x]=now; getdeep(x,0);
    return t[1]*t[2]*2+t[0]*t[0];
}

inline void sol(int x)
{
    ans+=cal(x,0); vis[x]=1;
    int sz=G[x].size();
    for (int i = 0; i < sz; ++i)
    {
        int y=G[x][i].to;
        if(vis[y]) continue;
        ans-=cal(y,G[x][i].val);
        root=0; sum=son[y];
        getroot(y,0); sol(root);
    }
}

int main(int argc, char const *argv[])
{
    n=read();
    for(int i = 1; i < n; ++i)
    {
        int u=read(),v=read(),w=read()%3;
        addedge(u,v,w);
    }
    f[0]=sum=n; getroot(1,0); sol(root);
    int t=gcd(ans,n*n);
    printf("%d/%d",ans/t,n*n/t);
    return 0;
}