题解 P1407

建图方式:旧关系女人连男人,现关系男人连女人(当然,反过来也可以)

原因可以这样考虑:

如果一个男的把女的绿了,那么这个女人就会去找一个她曾经交往过的男人,也就是在这种情况下,某种“影响”会顺着旧关系从女人传到男人,而此时这个男人又会顺着原关系把这种“影响”传给另一个女人;如果这种“影响”传回了那个男人,就说明那个男人也成功配对,并且这种“影响”的传递路径上正向边和反向边的个数相同(即被打破的关系数和新建立的关系数相同),所以这个婚姻就不稳定。

所以建完图后可以跑Tarjan,如果一对夫妇在同一个SCC中,这个婚姻就不稳定。

#include <cstdio>
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> M;
const int MAXN = 200000;
int cnt;
int head[MAXN], nxt[MAXN], to[MAXN];
int tot;
void ins(int u, int v)
{
	nxt[++cnt] = head[u];
	head[u] = cnt;
	to[cnt] = v;
}
int dfn[MAXN], low[MAXN], clo[MAXN];
int vis[MAXN], sta[MAXN], top;
void tarjan(int u)
{
	sta[++top] = u;
	dfn[u] = low[u] = ++tot;
	vis[u] = 1;
	for (int i = head[u], v = to[i]; i; i = nxt[i], v = to[i])
		if (!dfn[v])
		{
			tarjan(v);
			low[u] = min(low[u], low[v]);
		}
		else if (vis[v])
			low[u] = min(low[u], dfn[v]);
	if (low[u] == dfn[u])
	{
		clo[u] = u;
		vis[u] = 0;
		int y;
		while ((y = sta[top--]) != u)
			clo[y] = u, vis[y] = 0;
	}
}
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int n, m;
	int u, v;
	string girl, boy;
	cin >> n;
	for (int i = 1; i <= n; ++i)
	{
		cin >> girl;
		u = M[girl] = ++tot;
		cin >> boy;
		v = M[boy] = ++tot;
		ins(u, v);
	}
	cin >> m;
	tot = 0;
	for (int i = 1; i <= m; ++i)
	{
		cin >> girl;
		cin >> boy;
		v = M[girl];
		u = M[boy];
		ins(u, v);
	}
	for (int i = 1; i <= (n << 1); ++i)
		if (!dfn[i])
			tarjan(i);
	for (int i = 1; i <= n; ++i)
		if (clo[i << 1] == clo[(i << 1) - 1])
			cout << "Unsafe
";
		else
			cout << "Safe
";
	return 0;
}
原文地址:https://www.cnblogs.com/happyLittleRabbit/p/11728871.html