洛谷-1347
思路
注意:本体要求的不是一个拓扑排序就可以了,实际上是要求一条链的拓扑排序。
Code
#include <bits/stdc++.h>
using namespace std;
#define _u_u_ ios::sync_with_stdio(false), cin.tie(nullptr)
#define cf int _o_o_;cin>>_o_o_;for (int Case = 1; Case <= _o_o_;Case++)
#define SZ(x) (int)(x.size())
inline void _A_A_();
signed main() {_A_A_();return 0;}
using ll = long long;
// #define int long long
const int mod = 1e9 + 7;
const int maxn = 2e5 + 10;
const int N = 210, M = 5010;
const int inf = 0x3f3f3f3f;
struct edge {
int to, nxt;
}e[610];
int vis[26]; // 0->未访问;1->正在访问;-1->已经访问过
int idx, h[610], n , m, now=1;
void add(int u,int v) {
e[idx].to = v;
e[idx].nxt = h[u];
h[u] = idx++;
}
vector<int> res; // 记录拓扑序
set<int> st; // 记录现在已经出现过的点(实际上没啥用
bool dfs(int u) {
vis[u] = 1;
for (int i = h[u];i != -1;i =e[i].nxt) {
if (vis[e[i].to] == 1) return 1;
if (vis[e[i].to] == 0 && dfs(e[i].to)) return 1;
}
vis[u] = -1;
res.push_back(u);
return 0;
}
void topo() {
res.clear();
memset(vis, 0,sizeof vis);
for (auto i : st) { // 实际上可以从0到n-1
if (!vis[i] && dfs(i)) {
cout << "Inconsistency found after " << now << " relations.\n";
exit(0);
}
}
if (SZ(res) == n) {
int cnt = 0; // 这里用来判断是否是链
for (int i = n - 1;i >= 1;i -- ) { // 判断每两个相邻的节点是否连边
bool flag = 0;
int a = res[i], b = res[i - 1]; // 数据很水,这里写成a = i, b = i-1可以拿90分。
for (int k = h[a];k != -1;k = e[k].nxt) {
if (e[k].to == b) {
flag = 1;
}
}
if (flag) cnt++;
}
if (cnt == n - 1) { // 是链
cout << "Sorted sequence determined after " << now << " relations: ";
for (int i = n - 1;i >= 0;i--) {
char t = res[i] + 'A';
cout << t ;
}
cout << ".\n";
exit(0);
}
}
}
inline void _A_A_() {
#ifdef LOCAL
freopen("in.in", "r", stdin);
#endif
_u_u_;
memset(h, -1, sizeof h);
cin >> n >> m;
string s;
for (;now <= m;now++) {
cin >> s;
add(s[0] - 'A', s[2] - 'A');
st.insert(s[0] - 'A');
st.insert(s[2] - 'A');
topo();
}
cout << "Sorted sequence cannot be determined.\n";
}
标签:洛谷,cout,idx,int,res,1347,vis,st
From: https://www.cnblogs.com/FanWQ/p/16908728.html