[蓝桥杯][2013年第四届真题]危险系数(tarjan求割点)

 构造一颗以u为根的树,然后

一、求所有割点

二、对待每个可能的割点,要保证u和v都位于这个割点的两端

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define MAXN 1004
#define MOD 1000000009
#define INF 0x7ffffff
#define lowbit(x) (x)&(-x)

using namespace std;

int n,m;
int cnt;
int flagu,flagv;
int flag;
int vis[MAXN];
int dfn[MAXN];
int low[MAXN];
int first[MAXN];
vector vec;
struct EDGE{
    int to;
    int next;
}edge[4*MAXN];


inline void init(){
    cnt = 0;
    memset(dfn,0,sizeof(dfn));
    memset(low,0,sizeof(low));
    memset(first,-1,sizeof(first));
    vec.clear();
}

inline void add(int a,int b){
    edge[cnt].to = b;
    edge[cnt].next = first[a];
    first[a] = cnt++;
}

void Tarjan(int u,int f){
    vec.push_back(u); //vec存储树的节点
    ++cnt;
    dfn[u] = cnt;
    low[u] = cnt;
    int flag = 0;
    for(int i=first[u];i!=-1;i=edge[i].next){
        int v = edge[i].to;
        if(v == f && !flag){ //去重边
            flag = 1;
            continue;
        }
        if(!dfn[v]){
            Tarjan(v,u);
            low[u] = min(low[v],low[u]);
        }
        else if(v != f){
            low[u] = min(low[u],dfn[v]);
        }
    }
}

void DFS(int u,int v,int p,int step){
    vis[p] = 1;
    for(int i=first[p];i!=-1;i=edge[i].next){
        int to = edge[i].to;
        if(vis[to]) continue;
        if(to == u) flagu = 1;
        else if(to == v) flagv = 1;
        DFS(u,v,to,step+1);
        if(step == 1 && flagu+flagv == 1) flag = true;
    }
}

int main(){
    while(cin >> n >> m){
        init();
        int a,b;
        while(m--){
            cin >> a >> b;
            add(a,b);
            add(b,a);
        }
        int u,v;
        cin >> u >> v;
        cnt = 0;
        Tarjan(u,u); //以u为根构造树
        if(!dfn[v]) cout << -1 << endl; //v没有加入树,不连通
        else{
            int ans = 0;
            int len = vec.size();
            for(int i=0;i= dfn[p]){
                    memset(vis,0,sizeof(vis));
                    flagu = flagv = 0;
                    flag = false;
                    DFS(u,v,p,1);//是否满足u,v分别位于p点两端
                    if(flag) ++ans;
                }
            }
            cout << ans << endl;
        }
    }
    return 0;
}

 

你可能感兴趣的:(Tarjan算法,lanqiao)