Circle of Friends

来源:互联网 发布:淘宝助理官方网站下载 编辑:程序博客网 时间:2024/05/16 17:20

感觉强连通缩点越写越顺手了(笑

若是能在练习的时候每次都写一遍不要粘贴那真是极好的


强连通缩点后bfs求最短路


勉强算一个dfs套bfs?(笑




----------------------------我是代码的昏割线----------------------

#include<bits/stdc++.h>using namespace std;const int maxn = 112345;vector<int> edge[maxn];vector<int> dcc[maxn];int dfn[maxn],low[maxn],_cnt;int bel[maxn];stack<int> S;void init(int n){    for(int i=0;i<=n;i++){        edge[i].clear();        dcc[i].clear();    }    memset(dfn,-1,sizeof(dfn));    memset(low,-1,sizeof(low));    memset(bel,-1,sizeof(bel));    _cnt = 0;    while(S.empty()==false){        S.pop();    }}#define iter vector<int>::iteratorvoid dfs(int st){    dfn[st] = low[st] = _cnt++;    S.push(st);    for(iter it = edge[st].begin();it!=edge[st].end();it++){        int x = *it;        if(dfn[x] == -1){            dfs(x);            low[st] = min(low[st],low[x]);        }        else if(bel[x] == -1){            low[st] = min(low[st],dfn[x]);        }    }    if(low[st] == dfn[st]){        while(S.top() != st){            bel[S.top()] = st;            S.pop();        }        bel[st] = st;        S.pop();    }}int dis[maxn];queue<int> Q;int bfs(int st,int ed){    while(Q.empty()==false)        Q.pop();    memset(dis,-1,sizeof(dis));    dis[st] = st;    Q.push(st);    while(Q.empty()==false){        st = Q.front();        Q.pop();        if(st == ed){            return dis[st];        }        for(iter it = dcc[st].begin();it!=dcc[st].end();it++){            if(dis[*it] == -1){                dis[*it] = dis[st] +1;                Q.push(*it);            }        }    }    return -1;}int main(){    int T;    scanf("%d",&T);    int n,m;    while(T-- && ~scanf("%d %d",&n,&m)){        init(n);        int x,y;        while(m--){            scanf("%d %d",&x,&y);            edge[x].push_back(y);        }        for(int i=0;i<n;i++){            if(dfn[i] == -1){                dfs(i);            }        }        for(int i=0;i<n;i++){            for(iter it = edge[i].begin();it!=edge[i].end();it++){                int st = bel[i];                int ed = bel[*it];                if(st != ed){                    dcc[st].push_back(ed);                }            }        }        printf("%d\n",bfs(bel[0],bel[n-1]));    }    return 0;}


0 0
原创粉丝点击