P10944题解
思路
首先不想
然后用 拓扑排序 判断缩点后的图是否是满足是一张完全图即可既满足题目条件即可。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
int n, m, dfn[N], low[N], p[N], scc_cnt, tot;
bool vis[N];
stack<int> st;
vector<int> adj[N], v2[N];
int in[N], ou[N], op[N];
void tarjan(int x) {
dfn[x] = low[x] = ++tot;
st.push(x);
vis[x] = 1;
for (int y : adj[x]) {
if (!dfn[y]) {
tarjan(y);
low[x] = min(low[x], low[y]);
} else if (vis[y]) {
low[x] = min(low[x], dfn[y]);
}
}
if (dfn[x] == low[x]) {
scc_cnt++;
while (1) {
int o = st.top();
st.pop();
vis[o] = 0;
p[o] = scc_cnt;
if (o == x) break;
}
}
}
bool P() {
scc_cnt = tot = 0;
for (int i = 1; i <= n; i++) {
dfn[i] = low[i] = p[i] = 0;
vis[i] = 0;
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) {
tarjan(i);
}
}
for (int i = 1; i <= scc_cnt; i++) {
v2[i].clear();
in[i] = ou[i] = 0;
}
for (int x = 1; x <= n; x++) {
for (int y : adj[x]) {
if (p[x] != p[y]) {
v2[p[x]].push_back(p[y]);
in[p[y]]++;
ou[p[x]]++;
}
}
}
queue<int> q;
int cnt = 0;
for (int i = 1; i <= scc_cnt; i++) {
if (in[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
if (q.size() > 1) {
return 0;
}
int x = q.front();
q.pop();
op[++cnt] = x;
for (int y : v2[x]) {
if (--in[y] == 0) {
q.push(y);
}
}
}
for (int i = 1; i < cnt; i++) {
int x = op[i];
int y = op[i + 1];
bool f = 0;
for (int x : v2[x]) {
if (x == y) {
f = 1;
break;
}
}
if (!f) {
return 0;
}
}
return 1;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
int t;
cin >> t;
while (t--) {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
adj[i].clear();
}
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
adj[x].push_back(y);
}
if (P()) {
cout << "Yes\n";
} else {
cout << "No\n";
}
}
return 0;
}
/*
1
4 4
1 2
1 3
2 4
3 4
*/