zoukankan      html  css  js  c++  java
  • 点分治模板

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 #define inf 0x7fffffff
     6 using namespace std;
     7 int read()
     8 {
     9     int x=0,f=1;char ch=getchar();
    10     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    11     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    12     return x*f;
    13 }
    14 int n,K,cnt,sum,ans,root;
    15 int head[10005],deep[10005],d[10005],f[10005],son[10005];
    16 bool vis[10005];
    17 struct data{int to,next,v;}e[20005];
    18 void ins(int u,int v,int w)
    19 {e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].v=w;}
    20 void insert(int u,int v,int w)
    21 {ins(u,v,w);ins(v,u,w);}
    22 void getroot(int x,int fa)
    23 {
    24     son[x]=1;f[x]=0;
    25     for(int i=head[x];i;i=e[i].next)
    26     {
    27         if(e[i].to==fa||vis[e[i].to])continue;
    28         getroot(e[i].to,x);
    29         son[x]+=son[e[i].to];
    30         f[x]=max(f[x],son[e[i].to]);
    31     }
    32     f[x]=max(f[x],sum-son[x]);
    33     if(f[x]<f[root])root=x;
    34 }
    35 void getdeep(int x,int fa)
    36 {
    37     deep[++deep[0]]=d[x];
    38     for(int i=head[x];i;i=e[i].next)
    39     {
    40         if(e[i].to==fa||vis[e[i].to])continue;
    41         d[e[i].to]=d[x]+e[i].v;
    42         getdeep(e[i].to,x);
    43     }
    44 }
    45 int cal(int x,int now)
    46 {
    47     d[x]=now;deep[0]=0;
    48     getdeep(x,0);
    49     sort(deep+1,deep+deep[0]+1);
    50     int t=0,l,r;
    51     for(l=1,r=deep[0];l<r;)
    52     {
    53         if(deep[l]+deep[r]<=K){t+=r-l;l++;}
    54         else r--;
    55     }
    56     return t;
    57 }
    58 void work(int x)
    59 {
    60     ans+=cal(x,0);
    61     vis[x]=1;
    62     for(int i=head[x];i;i=e[i].next)
    63     {
    64         if(vis[e[i].to])continue;
    65         ans-=cal(e[i].to,e[i].v);
    66         sum=son[e[i].to];
    67         root=0;
    68         getroot(e[i].to,root);
    69         work(root);
    70     }
    71 }
    72 int main()
    73 {
    74     while(1)
    75     {
    76         ans=0;root=0;cnt=0;
    77         memset(vis,0,sizeof(vis));
    78         memset(head,0,sizeof(head));
    79         n=read();K=read();
    80         if(n==0)break;
    81         for(int i=1;i<n;i++)
    82          {
    83             int u=read(),v=read(),w=read();
    84             insert(u,v,w);
    85         }
    86         sum=n;f[0]=inf;
    87          getroot(1,0);
    88         work(root);
    89         printf("%d
    ",ans);
    90     }
    91     return 0;
    92 }
  • 相关阅读:
    C# extern关键字的用法
    C#自定义集合类(二)
    C#自定义集合类(一)
    LINQ中交集、并集、差集、去重(十四)
    LINQ中转换操作符(十三)
    Oracle实现连乘和求和
    适配器模式
    HTTP网络协议与手写Web服务容器
    代理模式
    设计模式的几条家规
  • 原文地址:https://www.cnblogs.com/myx12345/p/6517805.html
Copyright © 2011-2022 走看看