一名苦逼的OIer,想成为ACMer

Iowa_Battleship

POJ2762 Going from u to v or from v to u?

原题链接

显然在一个强连通分量里,任意两个点都可以到达,所以我们先用\(tarjan\)求强连通分量,并进行缩点。
对于缩点后的\(DAG\),必须满足是一条链,即在对该\(DAG\)进行拓扑排序的过程中,在任何时候都有且只有一个点是入度为\(0\)
因为若有两个点或以上的点同时出现入度为\(0\),那么这几个入度为\(0\)的点显然不能满足至少有一个点可以另一个点的条件。

#include<cstdio>
#include<cstring>
using namespace std;
const int N = 1010;
const int M = 6010;
struct eg {
	int x, y;
};
eg b[M];
int fi[N], di[M], ne[M], cfi[N], cdi[M], cne[M], dfn[N], low[N], sta[N], bl[N], ru[N], q[M], l, lc, ti, SCC, tp;
bool v[N];
inline int re()
{
	int x = 0;
	char c = getchar();
	bool p = 0;
	for (; c < '0' || c > '9'; c = getchar())
		p |= c == '-';
	for (; c >= '0' && c <= '9'; c = getchar())
		x = x * 10 + c - '0';
	return p ? -x : x;
}
inline int minn(int x, int y)
{
	return x < y ? x : y;
}
inline void add(int x, int y)
{
	di[++l] = y;
	ne[l] = fi[x];
	fi[x] = l;
}
inline void add_c(int x, int y)
{
	cdi[++lc] = y;
	cne[lc] = cfi[x];
	cfi[x] = lc;
}
void tarjan(int x)
{
	int i, y;
	dfn[x] = low[x] = ++ti;
	sta[++tp] = x;
	v[x] = 1;
	for (i = fi[x]; i; i = ne[i])
		if (!dfn[y = di[i]])
		{
			tarjan(y);
			low[x] = minn(low[x], low[y]);
		}
		else
			if (v[y])
				low[x] = minn(low[x], dfn[y]);
	if (!(dfn[x] ^ low[x]))
	{
		SCC++;
		do
		{
			y = sta[tp--];
			bl[y] = SCC;
			v[y] = 0;
		} while (x ^ y);
	}
}
bool topsort()
{
	int head = 0, tail = 0, i, x, y;
	for (i = 1; i <= SCC; i++)
		if (!ru[i])
			q[++tail] = i;
	if (tail - head > 1)
		return true;
	while (head ^ tail)
	{
		x = q[++head];
		for (i = cfi[x]; i; i = cne[i])
		{
			y = cdi[i];
			ru[y]--;
			if (!ru[y])
			{
				q[++tail] = y;
				if (tail - head > 1)
					return true;
			}
		}
	}
	return false;
}
int main()
{
	int i, n, m, x, y, t;
	t = re();
	while (t--)
	{
		n = re();
		m = re();
		memset(fi, 0, sizeof(fi));
		memset(cfi, 0, sizeof(cfi));
		memset(dfn, 0, sizeof(dfn));
		memset(low, 0, sizeof(low));
		memset(bl, 0, sizeof(bl));
		memset(ru, 0, sizeof(ru));
		l = lc = SCC = ti = 0;
		for (i = 1; i <= m; i++)
		{
			b[i].x = re();
			b[i].y = re();
			add(b[i].x, b[i].y);
		}
		for (i = 1; i <= n; i++)
			if (!dfn[i])
				tarjan(i);
		for (i = 1; i <= m; i++)
		{
			x = bl[b[i].x];
			y = bl[b[i].y];
			if (x ^ y)
			{
				add_c(x, y);
				ru[y]++;
			}
		}
		if (topsort())
			printf("No\n");
		else
			printf("Yes\n");
	}
	return 0;
}

posted on 2018-09-19 20:45  Iowa_Battleship  阅读(120)  评论(0编辑  收藏  举报

导航