链接:
https://vjudge.net/problem/POJ-2762
题意:
In order to make their sons brave, Jiajia and Wind take them to a big cave. The cave has n rooms, and one-way corridors connecting some rooms. Each time, Wind choose two rooms x and y, and ask one of their little sons go from one to the other. The son can either go from x to y, or from y to x. Wind promised that her tasks are all possible, but she actually doesn't know how to decide if a task is possible. To make her life easier, Jiajia decided to choose a cave in which every pair of rooms is a possible task. Given a cave, can you tell Jiajia whether Wind can randomly choose two rooms without worrying about anything?
给一个有向图,求判断能否选任意的两个点,有一条从u到v或v到u的路径。
思路:
先缩点形成一个DAG。只有当这个DAG是一条链的时候,才有u到v的路径。
代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
using namespace std;
const int MAXN = 1e3+10;
stack<int> St;
vector<int> G_new[MAXN], G[MAXN];
int Vis[MAXN];
int Dfn[MAXN], Low[MAXN];
int Fa[MAXN];
int Dis[MAXN];
int n, m;
int times, cnt;
void Tarjan(int x)
{
Dfn[x] = Low[x] = ++times;
Vis[x] = 1;
St.push(x);
for (int i = 0;i < G[x].size();i++)
{
int node = G[x][i];
if (Dfn[node] == 0)
{
Tarjan(node);
Low[x] = min(Low[x], Low[node]);
}
else if (Vis[node])
Low[x] = min(Low[x], Dfn[node]);
}
if (Dfn[x] == Low[x])
{
cnt++;
while (St.top() != x)
{
Fa[St.top()] = cnt;
Vis[St.top()] = 0;
St.pop();
}
Fa[St.top()] = cnt;
Vis[St.top()] = 0;
St.pop();
}
}
void Init()
{
for (int i = 1;i <= n;i++)
G[i].clear(), G_new[i].clear();
memset(Vis, 0, sizeof(Vis));
memset(Dis, 0, sizeof(Dis));
memset(Dfn, 0, sizeof(Dfn));
times = cnt = 0;
while (St.size())
St.pop();
}
bool Tupo()
{
int sum = 0;
stack<int> tu;
for (int i = 1;i <= cnt;i++)
if (Dis[i] == 0)
tu.push(i);
while (!tu.empty())
{
if (tu.size() > 1)
return false;
int x = tu.top();
sum++;
tu.pop();
for (int i = 0;i < G_new[x].size();i++)
{
int node = G_new[x][i];
if (--Dis[node] == 0)
tu.push(node);
}
}
return sum == cnt;
}
int main()
{
int t;
int l, r;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &m);
Init();
for (int i = 1;i <= m;i++)
{
scanf("%d%d", &l, &r);
G[l].push_back(r);
}
for (int i = 1;i <= n;i++)
if (Dfn[i] == 0)
Tarjan(i);
for (int i = 1;i <= n;i++)
{
for (int j = 0;j < G[i].size();j++)
{
int node = G[i][j];
if (Fa[i] != Fa[node])
{
Dis[Fa[node]]++;
G_new[Fa[i]].push_back(Fa[node]);
}
}
}
if (Tupo())
printf("Yes\n");
else
printf("No\n");
}
return 0;
}