E - Pursuit For Artifacts

主要是利用tarjan缩点,然后进行dfs

这篇代码是转载的,转载的地址-> http://blog.csdn.net/huanghongxun/

#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
#define clr(i,j) memset(i,j,sizeof(i))
#define FOR(i,j,k) for(int i=j;i<=k;++i)

const int N = 300005, M = 2 * N;

struct Graph {
    int head[N], forword[M], from[M], to[M], cost[M], val[N], dis[N], vis[N], cnt, id, n;
    int dfn[N], low[N], instack[N], stack[N], belong[N], bcc, top;

    Graph() : cnt(0) {}

    void add(int a, int b, int c) {
        forword[++cnt] = head[a]; from[cnt] = a; to[cnt] = b; cost[cnt] = c; head[a] = cnt;
        forword[++cnt] = head[b]; from[cnt] = b; to[cnt] = a; cost[cnt] = c; head[b] = cnt;
    }

    void tarjan(int u, int fa) {
        int i;
        dfn[u] = low[u] = ++id;
        instack[u] = 1; stack[++top] = u;
        for (i = head[u]; i; i = forword[i]) {
            if (to[i] == fa) continue;
            if (!dfn[to[i]]) {
                tarjan(to[i], u);
                low[u] = min(low[to[i]], low[u]);
            } else if (instack[to[i]])
                low[u] = min(dfn[to[i]], low[u]);
        }

        if (dfn[u] == low[u]) {
            ++bcc;
            do {
                i = stack[top--];
                belong[i] = bcc;
                instack[i] = 0;
            } while (i != u);
        }
    }

    void do_bcc() {
        id = 0; top = 0; bcc = 0;
        FOR(i,1,n) if (!dfn[i]) tarjan(i, 0);
    }

    void rebuild(Graph &out) {
        for (int i = 1; i <= cnt; i += 2)
            if (belong[from[i]] != belong[to[i]])
                out.add(belong[from[i]], belong[to[i]], cost[i]);
            else if (cost[i])
                out.val[belong[from[i]]] = 1;
    }

    bool calc(int x, int y) {
        queue<int> q; q.push(x);
        dis[x] = val[x]; vis[x] = 1;
        while (!q.empty()) {
            int u = q.front(), i; q.pop();
            for (i = head[u]; i; i = forword[i]) if (!vis[to[i]]) {
                if (dis[to[i]] < dis[u] + cost[i] + val[to[i]])
                    dis[to[i]] = dis[u] + cost[i] + val[to[i]];
                q.push(to[i]); vis[to[i]] = 1;
            }
        }
        return dis[y];
    }
} base, ne;

int main() {
    int n, m, a, b, c;
    scanf("%d%d", &n, &m);
    base.n = n;
    FOR(i,1,m) {
        scanf("%d%d%d", &a, &b, &c);
        base.add(a, b, c);
    }
    scanf("%d%d", &a, &b);
    base.do_bcc(); base.rebuild(ne);
    puts(ne.calc(base.belong[a], base.belong[b]) ? "YES" : "NO");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值