【tarjan双连通+LCA求割边数】POJ 3694

http://poj.org/problem?id=3694

08年的合肥赛区网络赛,这里求u,v的LCA只是常数时间复杂度

#define N 100010
struct edge{
    int v;
    int next;
}e[N*10];
int ecnt;
int head[N];
void init(){
    ecnt = 0;
    memset(head,-1,sizeof(head));
}
void add(int u,int v){
    e[ecnt].v = v;
    e[ecnt].next = head[u];
    head[u] = ecnt++;
    e[ecnt].v = u;
    e[ecnt].next = head[v];
    head[v] = ecnt++;
}
int low[N],dfn[N];
int fa[N];
bool cut[N];
int n,m;
int t;
int ans;
//tarjan求无向图双连通图
void tarjan(int u){
    low[u] = dfn[u] = ++t;
    int i;
    for(i=head[u];i!=-1;i=e[i].next){
        int v = e[i].v;
        if(v == fa[u])continue;
        if(!dfn[v]){
            fa[v] = u;
            tarjan(v);
            low[u] = min(low[u],low[v]);
            if(dfn[u]<low[v]){//v点最早的祖先不能得到它的父结点时,v就是割点
                cut[v] = 1;
                ans++;
            }
        } else low[u] = min(low[u],dfn[v]);//回溯时更新low[u],其中u是与割点v相邻且属于同一分量的点
    }
}
void LCA(int x,int y){//朴素LCA公共祖先,利用dfn的记录一直往上爬直到公共祖先
    while(dfn[x]<dfn[y]){
        if(cut[y]){
            cut[y] = 0;
            ans--;
        }
        y = fa[y];
    }
    while(dfn[x]>dfn[y]){
        if(cut[x]){
            cut[x] = 0;
            ans--;
        }
        x = fa[x];
    }
    while(x!=y){
        if(cut[x]){
            cut[x] = 0;
            ans--;
        }
        if(cut[y]){
            cut[y] = 0;
            ans--;
        }
        x = fa[x];
        y = fa[y];
    }
}
int main(){
    int ca=1;
    while(scanf("%d%d",&n,&m) && (n+m)){
        int i,j;
        init();
        while(m--){
            int a,b;
            scanf("%d%d",&a,&b);
            add(a,b);
        }
        t = ans = 0;
        memset(dfn,0,sizeof(dfn));
        memset(cut,0,sizeof(cut));
        tarjan(1);
        scanf("%d",&m);
        printf("Case %d:\n",ca++);
        while(m--){
            int a,b;
            scanf("%d%d",&a,&b);
            LCA(a,b);
            printf("%d\n",ans);
        }
        puts("");
    }
    return 0;
}

话说hdu有一模一样的题目,但总是RE栈溢出,可能数据有问题。。。





















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值