【题解】poj3417 Network 树上差分+lca

题目链接

Description

Yixght is a manager of the company called SzqNetwork(SN). Now she’s very worried because she has just received a bad news which denotes that DxtNetwork(DN), the SN’s business rival, intents to attack the network of SN. More unfortunately, the original network of SN is so weak that we can just treat it as a tree. Formally, there are N nodes in SN’s network, N-1 bidirectional channels to connect the nodes, and there always exists a route from any node to another. In order to protect the network from the attack, Yixght builds M new bidirectional channels between some of the nodes.

As the DN’s best hacker, you can exactly destory two channels, one in the original network and the other among the M new channels. Now your higher-up wants to know how many ways you can divide the network of SN into at least two parts.

Input

The first line of the input file contains two integers: N (1 ≤ N ≤ 100 000), M (1 ≤ M ≤ 100 000) — the number of the nodes and the number of the new channels.

Following N-1 lines represent the channels in the original network of SN, each pair (a,b) denote that there is a channel between node a and node b.

Following M lines represent the new channels in the network, each pair (a,b) denote that a new channel between node a and node b is added to the network of SN.

Output

Output a single integer — the number of ways to divide the network into at least two parts.

Sample Input

4 1
1 2
2 3
1 4
3 4

Sample Output

3

我们称每条附加边(x,y)都把树上x,y之间的路径上的每条边覆盖了一次。我们只需统计出每条“主要边”被覆盖了多少次。若第一步把被覆盖0次的主要边切断,则第二步可任意切断一条附加边。若第一步把被覆盖1次的主要边切断,则第二步方法唯一。利用树上差分算法,对每一条非树边(x,y),把f[x]++,f[y]++,f[lca(x,y]-=2,求出f[x]表示以x为根的子树中各节点的权值之和,就是x与它的父节点之间的树边被覆盖的次数(此处需要特判是否为根)。时间复杂度o(n+m)

#include
#include
#include
#include
using namespace std;
const int N=1e5+10;
const int DEP=25;
int n,m,hd[N],tot,f[N],fa[N][DEP],dep[N],dat[N];
struct Edge{
	int v,nx;
}e[N<<1];
inline void addedge(int u,int v)
{
	e[tot].v=v;
	e[tot].nx=hd[u];
	hd[u]=tot++;
}
void bfs()
{
	queueq;
	q.push(1);dep[1]=1;
	while(q.size())
	{
		int u=q.front();q.pop();
		for(int i=hd[u];~i;i=e[i].nx)
		{
			int v=e[i].v;
			if(dep[v])continue;
			dep[v]=dep[u]+1;
			fa[v][0]=u;
			for(int j=1;jdep[v])swap(u,v);
	for(int i=DEP-1;i>=0;i--)
	    if(dep[fa[v][i]]>=dep[u])v=fa[v][i];
	if(v==u)return u;
	for(int i=DEP-1;i>=0;i--)
	    if(fa[u][i]!=fa[v][i])u=fa[u][i],v=fa[v][i];
	return fa[u][0];
}
void dfs(int u,int father)
{
	dat[u]=f[u];
	for(int i=hd[u];~i;i=e[i].nx)
	{
		int v=e[i].v;
		if(v==father)continue;
		dfs(v,u);
		dat[u]+=dat[v];
	}
}
int main()
{
	//freopen("in.txt","r",stdin);
	memset(hd,-1,sizeof(hd));
	scanf("%d%d",&n,&m);
	int u,v,ans=0;
	for(int i=1;i

总结

树上差分好题

你可能感兴趣的:(poj,算法竞赛进阶指南,LCA,树上差分)