poj 3417(LCA应用)

Network
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 2496   Accepted: 726

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

Source

POJ Monthly--2007.10.06, Yang Mu
题目: http://poj.org/problem?id=3417
分析:这题很快就能想到统计边被环覆盖的次数,覆盖次数为0的边就是桥,答案+m,覆盖次数为一,说明它属于一条新边的环,答案+1。。。因为公共祖先的父辈不在其子辈的环中,所以新加边的公共祖先覆盖次数都要-2。。。讲懵了,详细看代码吧~~~
关于新加边存在x=y的情况,没判掉wa了n次阿~~~
代码:
#include
using namespace std;
const int mm=444444;
const int mn=111111;
int t[mm],p[mm];
int h[mn]={0},q[mn]={0},f[mn],mk[mn]={0};
bool vis[mn]={0};
int i,j,k,n,m,e,ans=0;
inline void add(int u,int v,int h[])
{
    t[e]=v,p[e]=h[u],h[u]=e++;
    t[e]=u,p[e]=h[v],h[v]=e++;
}
int find(int x)
{
    if(f[x]==x)return x;
    return f[x]=find(f[x]);
}
void tarjan(int u)
{
    int i,v;
    vis[f[u]=u]=1;
    for(i=q[u];i;i=p[i])
        if(vis[v=t[i]])mk[find(v)]-=2;
    for(i=h[u];i;i=p[i])
        if(!vis[v=t[i]])
        {
            tarjan(v),f[v]=u,mk[u]+=mk[v];
            if(mk[v]==1)++ans;
            if(mk[v]==0)ans+=m;
        }
}
void get(int &a)
{
    char c;
    while((c=getchar())<'0'||c>'9');
    for(a=0;c>='0'&&c<='9';c=getchar())a=a*10+c-'0';
}
int main()
{
    get(n),get(m);
    for(e=k=1;k


你可能感兴趣的:(图论,RMQ&LCA,network,pair,integer,input,manager,each)