poj3694-Network ( tarjin + LCA + 并查集 )

题目链接:

大致题意:
n点m条边,任意两个点直接或间接的连接;发现桥的不存在可以使得原本连通的变成不可能,然后又q次操作,问你每加入一条边,图中桥的数量。

解题报告:
显然是求桥(割边),有q次操作不可能每次都去求,必然TLE。
发现桥将原连通图分成了多个连通块,不妨用并查集维护每个连通块重新构造成树,每条树边都是桥,当每增加一条边时,若他们在同一连通块必然没有影响,反之可将两连通块合并,减少的桥的数量即他们最短路径上桥的数量,最短路径显然LCA

#define first f
#define second s
#define ll long long
#define mp make_pair
#define pb push_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
//#include <bits/stdc++.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cmath>
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int MOD=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=1e5+5;
const double eps=1e-6;
const double PI=acos(-1.0);
const double e=2.718281828459;

struct node
{
    int to,next;
}edge[maxn<<1];
int head[maxn],low[maxn],dfn[maxn],cnt,indx,ans;
int f[maxn],fa[maxn];

void add(int from,int to)
{
    edge[++cnt].next=head[from];
    edge[cnt].to=to;
    head[from]=cnt;
}
void init(int n)
{
    for(int i=1;i<=n;i++){f[i]=i;}
    mem(head,-1);mem(dfn,0);indx=ans=cnt=0;
}
int getfind(int x)
{
    return f[x]==x?x:f[x]=getfind(f[x]);
}
bool _union(int x,int y)
{
    int k1=getfind(x);
    int k2=getfind(y);
    if(k1!=k2){
        f[k2]=k1;
        return true;
    }
    return false;
}
void tarjin(int now,int pre)
{
    low[now]=dfn[now]=++indx;
    for(int i=head[now];~i;i=edge[i].next){
        int to=edge[i].to;
        if(!dfn[to]){
            fa[to]=now;
            tarjin(to,now);
            low[now]=min(low[now],low[to]);
            if(low[to]>dfn[now]){
                ans++;
            }
            else{
                _union(now,to);
            }
        }
        else if(pre!=to){
            low[now]=min(low[now],dfn[to]);
        }
    }
}
void LCA(int x,int y)
{
    if(dfn[x]<dfn[y]){swap(x,y);}
    while(dfn[x]>dfn[y]){
        if(_union(fa[x],x)){
            ans--;
        }
        x=getfind(fa[x]);
    }
    while(x!=y){
        if(_union(fa[y],y)){
            ans--;
        }
        y=getfind(fa[y]);
    }
}
int main()
{
    int n,m,u,v,q,T=0;
    while(~scanf("%d%d",&n,&m)){
        if(n==0&&m==0){break;}
        init(n);
        for(int i=1;i<=m;i++){
            scanf("%d%d",&u,&v);
            add(u,v);add(v,u);
        }
        tarjin(1,1);
        //cout<<ans<<endl;
        scanf("%d",&q);
        printf("Case %d:\n",++T);
        for(int i=1;i<=q;i++){
            scanf("%d%d",&u,&v);
            LCA(u,v);printf("%d\n",ans);
        }
        printf("\n");
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值