题解:P8405 [COCI 2021/2022 #6] Naboj
_LogicFish_qwq · · 题解
小清新思维题。
题意简述
给定一张有向图,这是“目标图”。
另有一张无方向的图,对它的边进行重定向,对于每次重定向:选定一个点
问,是否可以通过构造,使得开始的“无向图”经过重定向之后,得到目标图。
思路参考
如果对点不好处理,为什么不处理边呢?
首先想到对
对于一条边
- 如果最后处理的是
a ,那么让a 指向b ,题目里就是充正电,输出1 。 - 如果最后处理的是
b ,那么让b 被a 指过去,也就是充负电,输出0 。
两个充电方法都要考虑?这太复杂了。由于这两种方法唯一的区别是定的方向,且只有最后定向的点,它进行的重定向才会生效,不妨让所有点充正电好了。
那么如果一条边
所以我们考虑按“处理的顺序”连边:连一条
那么什么是无解的情况?相互依赖。也就是说,
代码部分
代码还是很好写的,唯一的问题是方向。
- 如果输出“全正电”的方法,建边的方向和原图方向相反。
- 如果输出“全负电”的方法,建边的方向和原图方向相同。
其它没了,基本上是板子题。 :::success[AC Code]
//Someone tell Vedal there is a problem with my AI.
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#define int long long
#define rep(v, s, e) for(int v=(s);v<=(e);v++)
#define dec(v, e, s) for(int v=(e);v>=(s);v--)
const int MAXN = 2e5;
int n, m;
std::vector<int>graph[MAXN + 5];
int deg[MAXN + 5];
int ord[MAXN + 5], tot, ans[MAXN + 5];
std::queue<int>q;
bool valid;
inline bool TopoSort();
void Init(), PreSolve(), Input(), Solve(), Answer(), AC();
signed main(){
AC();
return 0;
}
void Init(){
std::ios::sync_with_stdio(false),
std::cin.tie(0),std::cout.tie(0);
#ifndef ONLINE_JUDGE
std::freopen("FILE.in" , "r", stdin );
std::freopen("FILE.out", "w", stdout);
#endif
}
void AC(){
Init();
int T = 1;
//std::cin >> T;
while(T--){
PreSolve();
Input();
Solve();
Answer();
}
}
void PreSolve(){
rep(i, 1, MAXN) ans[i] = i;
}
void Input(){
std::cin >> n >> m;
int x, y;
rep(i, 1, m){
std::cin >> x >> y;
graph[y].push_back(x), deg[x]++;//建的边是反着的!
}
}
void Solve(){
valid = TopoSort();
std::sort(ans + 1, ans + n + 1, [](int x, int y){
return ord[x] < ord[y];//离散化
});
}
void Answer(){
if(!valid) return (void)(std::cout << "-1");
std::cout << n << "\n";
rep(i, 1, n) std::cout << ans[i] << " 1\n";
}
inline bool TopoSort(){
rep(i, 1, n) if(!deg[i]) q.push(i);
while(!q.empty()){
int x = q.front(); q.pop();
ord[x] = ++tot;
for(int y: graph[x]) if(!(--deg[y])) q.push(y);
}
return tot == n;//如果 n 个点全部跑完,就说明图中没有环。否则一定有环。
}
:::
:::info[闲话]
有人问我,“如果选择负电,就不用反向建边了啊,为什么你当时选的是正电?”。
呃,这个,因为我是