主要是利用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;
}