首页 > 其他分享 >POJ 1987 Distance Statistics (树上点分治)

POJ 1987 Distance Statistics (树上点分治)

时间:2023-04-13 22:33:23浏览次数:50  
标签:1987 Statistics const Distance int tot dep MAXN include


题目地址:POJ 1987
点分治模板题,跟POJ 1741几乎一样,。。
代码如下:

#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <stdlib.h>
#include <map>
#include <set>
#include <stdio.h>
#include <time.h>
using namespace std;
#define LL __int64
#define pi acos(-1.0)
//#pragma comment(linker, "/STACK:1024000000")
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
const double eqs=1e-9;
const int MAXN=50000+10;
int head[MAXN], cnt, ans, min1, root, tot;
int siz[MAXN], dep[MAXN], vis[MAXN], d[MAXN];
int n, k;
struct node {
        int v, w, next;
} edge[MAXN<<1];
void add(int u, int v, int w)
{
        edge[cnt].v=v;
        edge[cnt].w=w;
        edge[cnt].next=head[u];
        head[u]=cnt++;
}
void init()
{
        memset(head,-1,sizeof(head));
        cnt=ans=0;
        memset(vis,0,sizeof(vis));
}
void getroot(int u, int fa, int s)
{
        int i, max1=0;
        siz[u]=1;
        for(i=head[u]; i!=-1; i=edge[i].next) {
                int v=edge[i].v;
                if(v==fa||vis[v]) continue ;
                getroot(v,u,s);
                siz[u]+=siz[v];
                max1=max(max1,siz[v]);
        }
        max1=max(max1,s-siz[u]);
        if(min1>max1) {
                min1=max1;
                root=u;
        }
}
void getdep(int u, int fa)
{
        d[tot++]=dep[u];
        siz[u]=1;
        for(int i=head[u]; i!=-1; i=edge[i].next) {
                int v=edge[i].v;
                if(v==fa||vis[v]) continue ;
                dep[v]=dep[u]+edge[i].w;
                getdep(v,u);
                siz[u]+=siz[v];
        }
}
int Cal(int u, int len)
{
        int l, r, res=0;
        tot=0;
        dep[u]=len;
        getdep(u,-1);
        sort(d,d+tot);
        r=tot-1;
        for(l=0; l<tot; l++) {
                while(d[r]+d[l]>k) r--;
                if(r<=l) break;
                res+=r-l;
        }
        return res;
}
void work(int u)
{
        ans+=Cal(u,0);
        vis[u]=1;
        for(int i=head[u]; i!=-1; i=edge[i].next) {
                int v=edge[i].v;
                if(vis[v]) continue ;
                ans-=Cal(v,edge[i].w);
                min1=INF;
                getroot(v,-1,siz[v]);
                work(root);
        }
}
int main()
{
        int u, v, w, i, m;
        char c;
        scanf("%d%d",&n,&m);
        init();
        for(i=0; i<m; i++) {
                scanf("%d%d%d %c",&u,&v,&w,&c);
                add(u,v,w);
                add(v,u,w);
        }
        scanf("%d",&k);
        min1=INF;
        getroot(1,-1,n);
        work(root);
        printf("%d\n",ans);
        return 0;
}


标签:1987,Statistics,const,Distance,int,tot,dep,MAXN,include
From: https://blog.51cto.com/u_16070138/6188466

相关文章