标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1097 Accepted Submission(s): 366
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<string> #include<algorithm> #include<queue> #include<vector> #include<stack> #include<map> #include<set> using namespace std; vector<int> e[100005]; struct node { int x,y,z; }mp[100005]; int n,m,vis[100005],deep[100005],f[100005][30],mark[100005]; void init() { for(int i=1;i<=n;i++) { vis[i]=0; deep[i]=0; mark[i]=0; e[i].clear(); } memset(f,0,sizeof(f)); } void dfs(int u) { vis[u]=1; for(int i=0;i<e[u].size();i++) { int v=e[u][i]; if(v==f[u][0]) continue; if(!vis[v]) { deep[v]=deep[u]+1; f[v][0]=u; dfs(v); } } } void bz() { for(int i=1;(1<<i)<=n;i++) { for(int j=1;j<=n;j++) { f[j][i]=f[f[j][i-1]][i-1]; } } } bool cmp(node a,node b) { return deep[a.z]>deep[b.z]; } int LCA(int x,int y) { int i,j; if(deep[x]<deep[y]) swap(x,y); for(i=0;(1<<i)<=deep[x];i++); i--; for(j=i;j>=0;j--) { if(deep[x]-(1<<j)>=deep[y]) { x=f[x][j]; } } if(x==y) return y; for(j=i;j>=0;j--) { if(f[x][j]!=f[y][j]) { x=f[x][j]; y=f[y][j]; } } return f[x][0]; } void col(int u) { mark[u]=1; for(int i=0;i<e[u].size();i++) { int v=e[u][i]; if(deep[v]==deep[u]+1&&!mark[v]) col(v); } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { init(); for(int i=1;i<n;i++) { int x,y; scanf("%d%d",&x,&y); e[x].push_back(y); e[y].push_back(x); } f[1][0]=1; deep[1]=1; dfs(1); bz(); for(int i=0;i<m;i++) { int x,y; scanf("%d%d",&x,&y); mp[i].x=x,mp[i].y=y,mp[i].z=LCA(x,y); } int ans=0; sort(mp,mp+m,cmp); for(int i=0;i<m;i++) { if(!mark[mp[i].x]&&!mark[mp[i].y]) { ans++; col(mp[i].z); } } printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/water-full/p/4502642.html