pat-top 1008. Airline Routes (35)

2 篇文章 0 订阅
1 篇文章 0 订阅

https://www.patest.cn/contests/pat-t-practise/1008


参考了https://zh.wikipedia.org/wiki/Tarjan%E7%AE%97%E6%B3%95

code 来自于http://blog.csdn.net/jtjy568805874/article/details/50759540

题意是求在有向图中的两个点是否在一个强连通分量上, 使用tarjan算法,为每个点打标签 是同一个强连通的lowlink 与这个强连通的“根”的lowlink 相同。


#include <cstdio>
#include <stack>
#include <algorithm>
using namespace std;

#define rep(i,f,t) for(i= f;i<t;i++)
const int maxn = 2e5; //There is 1e4 nodes, 6e4 edges. There is 1.2e5 nodes at most in adjective table
int ft[maxn], nt[maxn], v[maxn], tot; // ft: first, nt:next, v:vertex, tot: total node number, new node = v[tot++]; 
int low[maxn],lowlink[maxn],t; // t: the index of dfs sequence
stack<int> s;

void tarjan(int x) {
	low[x] = lowlink[x] = ++t; // prevent give '0' to low[x];
	s.push(x);
	for (int i = ft[x]; i != -1; i = nt[i]) 
	{
		if (!low[v[i]]) {
			tarjan(v[i]);
			lowlink[x] = min(lowlink[x], lowlink[v[i]]);
		}
		else lowlink[x] = min(lowlink[x], low[v[i]]);
	}
	if (low[x] == lowlink[x]) {
		int u;
		do {
			u = s.top(); s.pop();
			lowlink[u] = lowlink[x];
		} while (u != x);
	}
}


int main()
{
	//freopen("out.txt", "w", stdout);
	int n, m, x, y, i;
	scanf("%d %d", &n, &m);
	tot = t = 0;
	rep(i, 1, n + 1) ft[i] = -1, low[i] = 0;
	while (m--) {
		scanf("%d %d", &x, &y);
		//new node in adjective table
		v[tot] = y; nt[tot] = ft[x]; ft[x] = tot++;
	}
	rep(i, 1, n + 1) if (!low[i]) tarjan(i);
	scanf("%d", &m);
	while (m--) {
		scanf("%d %d", &x, &y);
		printf("%s\n", lowlink[x] == lowlink[y] ? "Yes": "No");
	}
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值