zoukankan      html  css  js  c++  java
  • 「CJOJ2722」Ping


    Sample Input


    5 4
    2 1
    5 3
    3 1
    4 3
    2
    2 4
    3 2

    Sample Output


    1

    Hint


    题解


    这道题目显然把每一段查询的路径求出来(即求LCA),然后将LCA排序,最后算一遍就行了

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<iostream>
    #include<algorithm>
    #define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout);
    #define re register
    using namespace std;
    inline int gi(){
    	int sum=0,f=1;char ch=getchar();
    	while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
    	while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
    	return sum*f;
    }
    const int maxn=100010;
    struct gjh{
    	int to,nxt;
    }e[maxn<<1],e1[maxn<<3];
    int dfs[maxn];
    struct node{
    	int x,y,z;
    	bool operator <(node b)const{
    		return dfs[z]>dfs[b.z];
    	}
    }lca[maxn<<2];
    int front[maxn],cnt,p[maxn],k,bj[maxn];
    int fa[maxn],lcah[maxn],cou;
    void Add(int u,int v){
    	e[++cnt]=(gjh){v,front[u]};front[u]=cnt;
    	e[++cnt]=(gjh){u,front[v]};front[v]=cnt;
    }
    void Ad(int x,int y){
    	e1[++cnt]=(gjh){y,p[x]};p[x]=cnt;
    	e1[++cnt]=(gjh){x,p[y]};p[y]=cnt;
    }
    int find(int x){
    	if(lcah[x]!=x)lcah[x]=find(lcah[x]);
    	return lcah[x];
    }
    void tarjan(int u){
    	bj[u]=1;lcah[u]=u;dfs[u]=++cnt;
    	for(int i=front[u];i;i=e[i].nxt){
    		int v=e[i].to;
    		if(v!=fa[u]){
    			fa[v]=u;
    			tarjan(v);
    			lcah[v]=u;
    		}
    	}
    	for(int i=p[u];i;i=e1[i].nxt)
    		if(bj[e1[i].to])
    			lca[++cou]=(node){u,e1[i].to,find(e1[i].to)};
    }
    int cmp(node a,node b){
    	return a.z>b.z;
    }
    int a[maxn<<2],ans,flag[maxn];
    void dfs1(int u){
    	flag[u]=1;
    	for(int i=front[u];i;i=e[i].nxt){
    		int v=e[i].to;
    		if(v!=fa[u])dfs1(v);
    	}
    }
    int main(){
    	int i,j,n,m;
    	n=gi();m=gi();
    	for(i=1;i<=m;i++){
    		int u=gi(),v=gi();Add(u,v);
    	}
    	k=gi();cnt=0;
    	for(i=1;i<=k;i++){
    		int x=gi(),y=gi();
    		Ad(x,y);
    	}
    	fa[1]=1;cnt=0;
    	tarjan(1);
    	sort(lca+1,lca+cou+1);
    	for(i=1;i<=cou;i++)
    		if(!flag[lca[i].x] && !flag[lca[i].y]){
    			a[++ans]=lca[i].z;
    			dfs1(lca[i].z);
    		}
    	printf("%d
    ",ans);
    	return 0;
    }
    
    
  • 相关阅读:
    CodeForces 785D Anton and School
    CodeForces 785C Anton and Fairy Tale
    CodeForces 785B Anton and Classes
    CodeForces 785A Anton and Polyhedrons
    爱奇艺全国高校算法大赛初赛C
    爱奇艺全国高校算法大赛初赛B
    爱奇艺全国高校算法大赛初赛A
    EOJ 3265 七巧板
    EOJ 3256 拼音魔法
    EOJ 3262 黑心啤酒厂
  • 原文地址:https://www.cnblogs.com/cjgjh/p/9364218.html
Copyright © 2011-2022 走看看