poj 1987 树的分治

思路:1741的A1送 1.

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#define Maxn 40010
#define Maxm 80010
#define inf 0x7fffffff
using namespace std;
int head[Maxn],vi[Maxn],e,ans,num,k,n,m;
int mx[Maxn],mi,dis[Maxn],root,size[Maxn];
struct Edge{
int u,v,val,next;
}edge[Maxm];
void init()
{
memset(vi,,sizeof(vi));
memset(head,-,sizeof(head));
memset(mx,,sizeof(mx));
memset(dis,,sizeof(dis));
e=ans=;
}
void add(int u,int v,int val)
{
edge[e].u=u,edge[e].v=v,edge[e].val=val,edge[e].next=head[u],head[u]=e++;
edge[e].u=v,edge[e].v=u,edge[e].val=val,edge[e].next=head[v],head[v]=e++;
}
void dfssize(int u,int fa)
{
int i,v;
size[u]=;
mx[u]=;
for(i=head[u];i!=-;i=edge[i].next)
{
v=edge[i].v;
if(v!=fa&&!vi[v])
{
dfssize(v,u);
size[u]+=size[v];
if(size[v]>mx[u]) mx[u]=size[v];
}
}
}
void dfsroot(int r,int u,int fa)
{
int v,i;
if(size[r]-size[u]>mx[u]) mx[u]=size[r]-size[u];
if(mx[u]<mi) mi=mx[u],root=u;
for(i=head[u];i!=-;i=edge[i].next)
{
v=edge[i].v;
if(v!=fa&&!vi[v])
{
dfsroot(r,v,u);
}
}
}
void dfsdis(int u,int d,int fa)
{
int i,v;
dis[++num]=d;
for(i=head[u];i!=-;i=edge[i].next)
{
v=edge[i].v;
if(v!=fa&&!vi[v])
{
dfsdis(v,d+edge[i].val,u);
}
}
}
int calc(int u,int d)
{
int i,j,ret=;
num=;
dfsdis(u,d,);
sort(dis+,dis++num);
i=;j=num;
while(i<j)//单调求点对
{
while(dis[i]+dis[j]>k&&i<j)
j--;
ret+=j-i;
i++;
}
return ret;
}
void dfs(int u)
{
int i,v;
mi=n;
dfssize(u,);
dfsroot(u,u,);
ans+=calc(root,);
vi[root]=;
for(i=head[root];i!=-;i=edge[i].next)
{
v=edge[i].v;
if(!vi[v])
{
ans-=calc(v,edge[i].val);
dfs(v);
}
}
}
int main()
{
int i,j,u,v,val;
char cc;
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
for(i=;i<=m;i++)
{
scanf("%d%d%d %c",&u,&v,&val,&cc);
add(u,v,val);
}
scanf("%d",&k);
dfs();
printf("%d\n",ans);
}
return ;
}
上一篇:CSS代码重构与优化之路


下一篇:软件工程 in MSRA Code Search-第二次结对编程