poj2762 Going from u to v or from v to u?

对于任意两个点x,y要存在一条x->y或者y->x的路径。显然是缩点然后判断是不是一条链。

const int maxn = 1010;
int n, m;
vector<vector<int> > G;
int dfn[maxn], low[maxn], depth;
int belong[maxn], block;
int in[maxn], mark[maxn];
stack<int> st;
int head[maxn], pnt[maxn<<3], nxt[maxn<<3], ecnt;
void addedge(int u,int v) {
    pnt[ecnt] = v, nxt[ecnt] = head[u], head[u] = ecnt++;
}
void tarjan(int u) {
    dfn[u] = low[u] = ++depth;
    st.push(u), mark[u] = 1;
    int Size = G[u].size();
    for (int i = 0;i < Size;++i) {
        int v = G[u][i];
        if (dfn[v] == 0) {
            tarjan(v);
            low[u] = min(low[v], low[u]);
        }else if (mark[v]) low[u] = min(low[u], dfn[v]);
    }

    if (dfn[u] == low[u]) {
        block++;
        while(true) {
            int x = st.top();
            st.pop();
            belong[x] = block;
            mark[x] = 0;
            if (x == u) break;
        }
    }

    return ;
}
int ans;
void dfs(int u) {
    ans++;
    mark[u] = 1;
    for (int i = head[u]; ~i;i = nxt[i]) {
        int v = pnt[i];
        if (!mark[v]) {
            // ans++;
            dfs(v);
            return ;
        }
    }
}
int main(int argc, const char * argv[])
{    
    // freopen("in.txt","r",stdin);
    // freopen("out.txt","w",stdout);
    // clock_t _ = clock();

    int t;
    cin >> t;
    while(t--) {
        scanf("%d%d", &n, &m);
        G.clear();G.resize(n + 2);
        int u, v;
        while(m--) {
            scanf("%d%d", &u, &v);
            G[u].push_back(v);
        }
        memset(dfn, 0,sizeof dfn), depth = block = 0;
        memset(mark, 0,sizeof mark);
        for (int i = 1;i <= n;++i)
            if (dfn[i] == 0) tarjan(i);

        memset(head, -1,sizeof head), ecnt = 0;
        memset(in, 0,sizeof in);
        for (int i = 1;i <= n;++i) {
            for (int j = 0;j < G[i].size();++j) {
                u = i, v = G[i][j];
                if (belong[u] != belong[v]) {
                    addedge(belong[u], belong[v]);
                    in[belong[v]]++;
                }
            }
        }
        ans = 0;
        for (int i = 1;i <= block;++i)
            if (in[i] == 0) {dfs(i);break;}
        if (ans == block) puts("Yes");
        else puts("No");
    }

    // printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值