圆方树 - OI Wiki (oi-wiki.org)
F-Fief_"蔚来杯"2022牛客暑期多校训练营3(重现赛)@山川四月 (nowcoder.com)
题目大意:给定一个无向图,每次询问两点x, y,求是否存在一个n的排列,使得第一个元素为x,最后一个元素为y,且排列的任意一个前缀、任意一个后缀都连通。
其实就是求这两个点是否存在两个不相同的路径,同时两者路径的交集是n
可以用圆方树缩点将其变成一颗树,再判断这颗树是否是一条链,x,y是否在这条链的两侧
using namespace std;
#define int long long//__int128 2^127-1(GCC)
#define PII pair<int,int>
const int inf = 0x3f3f3f3f3f3f3f3f, N = 100000 + 5, mod = 1e9 + 7, M = 200000 + 5;
int cnt;
vector<int>G[N], T[N * 2];
int stk[N], tp;
int dfn[N], low[N], dfc;
void Tarjan(int u) {//printf(" Enter : #%lld\n", u);low[u] = dfn[u] = ++dfc; // low 初始化为当前节点 dfnstk[++tp] = u; // 加入栈中for (int v : G[u]) { // 遍历 u 的相邻节点if (!dfn[v]) { // 如果未访问过Tarjan(v); // 递归low[u] = std::min(low[u], low[v]); // 未访问的和 low 取 minif (low[v] == dfn[u]) { // 标志着找到一个以 u 为根的点双连通分量++cnt; // 增加方点个数//printf(" Found a New BCC #%lld.\n", cnt - n);// 将点双中除了 u 的点退栈,并在圆方树中连边for (int x = 0; x != v; --tp) {x = stk[tp];T[cnt].push_back(x);T[x].push_back(cnt);//printf(" BCC #%lld has vertex #%lld\n", cnt - n, x);}// 注意 u 自身也要连边(但不退栈)T[cnt].push_back(u);T[u].push_back(cnt);//printf(" BCC #%lld has vertex #%lld\n", cnt - n, u);}}elselow[u] = std::min(low[u], dfn[v]); // 已访问的和 dfn 取 min}//printf(" Exit : #%lld : low = %lld\n", u, low[u]);//printf(" Stack:\n ");//for (int i = 1; i <= tp; ++i) printf("%lld, ", stk[i]);//puts("");
}
signed main()
{ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0);int n, m;cin >> n >> m;cnt = n;while (m--) {int u, v;cin >> u >> v;G[u].push_back(v);G[v].push_back(u);}int ok = 0;for (int u = 1; u <= n; ++u)if (!dfn[u]) Tarjan(u), --tp, ok++;vector<int>dep(cnt + 1);int tot_num = 0;for (int i = n + 1; i <= cnt; i++) {int num = 0;for (auto w : T[i]) {if (T[w].size() == 1) continue;num++;}if (num == 1 || num == 0) {queue<int>que;que.push(i);dep[i] = 1;while (que.size()) {auto t = que.front();tot_num++;que.pop();for (auto w : T[t]) {if (T[w].size() == 1) continue;if (dep[w]) continue;dep[w] = dep[t] + 1;que.push(w);}}break;}}vector<int>flag(n + 1);for (int i = 1; i <= n; i++) {if (T[i].size() == 1) {if (dep[T[i][0]] == 1) {flag[i] = 1;}if (dep[T[i][0]] == tot_num) {flag[i] = tot_num;}}}int Q;cin >> Q;while (Q--) {int u, v;cin >> u >> v;if (ok != 1) {cout << "NO\n";}else if (flag[u] == 1 && flag[v] == tot_num) {cout << "YES\n";}else if (flag[v] == 1 && flag[u] == tot_num) {cout << "YES\n";}else {cout << "NO\n";}}
}//8 9
//1 2
//1 3
//2 4
//3 4
//4 5
//4 6
//5 7
//6 7
//7 8