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 11 22 31 43 4
Sample Output
3
题意:
n个点,成一棵树,m条新边,问在原先的树中和m条新边中去掉一条边使正好分成两部分的方案
题解:
对于一组新边(u,v),就相当于 对u->v的所有原来的边进行一次覆盖,
若(u1,v1)正好有一次覆盖则这条边会对答案有1的影响。
若覆盖次数>1 则无法成立。对于那些覆盖次数为0的则对答案有m的贡献。
这样我们就要求覆盖的次数,可用LCA覆盖,dfs根节点算答案。
注意细节!!!!!
#include#include #include using namespace std;const int MAXN=110000;const int MAXM=21;struct E{int u,v,next;}mm[MAXN<<1];int n,m,len,dep[MAXN],fa[MAXN][MAXM],cnt[MAXN],h[MAXN],ans;inline void ins(int u,int v){ ++len; mm[len].u=u;mm[len].v=v;mm[len].next=h[u];h[u]=len;}void dfs(int u,int f){ dep[u]=dep[f]+1;fa[u][0]=f; for(int k=h[u] ; k ; k=mm[k].next){ int v=mm[k].v; if(v!=f){ dfs(v,u); } }}int LCA(int x,int y){ if(dep[x] < dep[y]) swap(x,y); for(int j=MAXM-1;j>=0;j--) if(dep[fa[x][j]] >= dep[y]) x=fa[x][j]; if(x==y) return x; for(int j=MAXM-1;j>=0;j--) if(fa[x][j] != fa[y][j]) x=fa[x][j],y=fa[y][j]; return fa[x][0];} void dfs1(int x,int f){ for(int k=h[x] ; k ; k=mm[k].next){ int y=mm[k].v; if(y!=f){ dfs1(y,x); cnt[x]+=cnt[y]; } } if(x==1) return ; if(cnt[x]==1) ans+=1; if(cnt[x]==0) ans+=m; } int main(){// freopen("D.in","r",stdin); scanf("%d%d",&n,&m); len=0;memset(h,0,sizeof h); for(int i=1,u,v;i