您的位置:首页 > 其它

poj 1741 简单树分治

2016-06-01 23:36 316 查看
Tree
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 17135 Accepted: 5586
DescriptionGive a tree with n vertices,each edge has a length(positive integer less than 1001). Define dist(u,v)=The min distance between node u and v. Give an integer k,for every pair (u,v) of vertices is called valid if and only if dist(u,v) not exceed k. Write a program that will count how many pairs which are valid for a given tree. InputThe input contains several test cases. The first line of each test case contains two integers n, k. (n<=10000) The following n-1 lines each contains three integers u,v,l, which means there is an edge between node u and v of length l. The last test case is followed by two zeros. OutputFor each test case output the answer on a single line.Sample Input
5 41 2 31 3 11 4 23 5 10 0
Sample Output
8
题意是给定一棵树问你树里有多少条简单路径满足路径长度小于等于k。假设我现在选定了一个点x,要求所有经过x的且长度小于等于k的路径数量是很好求的,把每个点到x的距离求出来,排序一下,然后双指针搞一搞就好了。那么对于不经过x的路径。递归下去做就好了。为了减少递归层数。把重心当做x。那么递归层数就只有logn层了,最终复杂度是nlog^2n#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;struct EDGE{int to,next;__int64 val;EDGE(){}EDGE(const int &to,const int &next,const __int64 &val):to(to),next(next),val(val){}}e[202020];int head[101010],tot;int n;int k;int s[101010];bool mark[101010];int find_root(int u,int fa,int mxsize){s[u]=1;int maxn=0;for(int i=head[u];i>=0;i=e[i].next){if(e[i].to==fa||mark[e[i].to])continue;int may=find_root(e[i].to,u,mxsize);if(may!=-1)return may;s[u]+=s[e[i].to];maxn=max(maxn,s[e[i].to]);}if(maxn<mxsize-s[u])maxn=mxsize-s[u];if(maxn*2<=mxsize)return u;return -1;}int all[101010];int ts[101010],tp;void get_depth(int u,int fa,__int64 sum){ts[tp++]=sum;s[u]=1;for(int i=head[u];i>=0;i=e[i].next){if(e[i].to==fa||mark[e[i].to])continue;get_depth(e[i].to,u,sum+e[i].val);s[u]+=s[e[i].to];}}__int64 solve(int rt){mark[rt]=true;__int64 ret=0;tot=0;for(int i=head[rt];i>=0;i=e[i].next){int v=e[i].to;if(!mark[v]){tp=0;get_depth(v,v,e[i].val);sort(ts,ts+tp);int t=0,w=tp-1;while(t<w){if(ts[w]+ts[t]>k){w--;}else {ret-=(w-t);t++;}}for(int j=0;j<tp;j++){all[tot]=ts[j];if(all[tot]<=k)ret++;tot++;}}}int t=0,w=tot-1;sort(all,all+tot);while(t<w){if(all[w]+all[t]>k){w--;}else {ret+=(w-t);t++;}}for(int i=head[rt];i>=0;i=e[i].next){int v=e[i].to;if(!mark[v]){int rt=find_root(v,v,s[v]);ret+=solve(rt);}}return ret;}int main(){while(~scanf("%d%I64d",&n,&k)){if(n==0)break;tot=0;for(int i=1;i<=n;i++){head[i]=-1;mark[i]=false;}for(int i=1;i<n;i++){int u,v;__int64 w;scanf("%d%d%I64d",&u,&v,&w);e[tot]=EDGE(v,head[u],w);head[u]=tot++;e[tot]=EDGE(u,head[v],w);head[v]=tot++;}int rt;rt=find_root(1,-1,n);__int64 ans=solve(rt);printf("%I64d\n",ans);}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: