题解:P12455 [INOI Team Selection 2021] Andarzgu
20111019Yu · · 题解
小故事
写的时候不知道拓扑 DP 可以不只从上一个节点转移,还能从可到达他的所有点转移过来,挂了
思路
强连通分量
首先考虑对于强连通分量怎么求答案。
注意到某些点可以不选很麻烦,于是给他加上自环。
那么题意变成:有向图求环分解方案数。
有一个很经典的 trick 是这个的答案是图的邻接矩阵的积和式,在模
注意到每一项要么是
那么就得到了
有向图
考虑 tarjan 后的拓扑结构。
在每个 scc 处计算贡献,为了不算重只在当前 scc 不全为自环时计算。
转移类似,是从之前的所有 scc 不全为自环时转移。
这一部分也是
code
::::success[
#include <bits/stdc++.h>
using namespace std;
int n, m, x, y, a[5005][5005], scc[5005], low[5005], dfn[5005], hd, st[5005], in, cnt, ans[5005], sum = 1, degree[5005], dp[5005], bel[5005], c[5005];
vector<int> vec[5005];
bool vis[5005];
struct road{
int x, y;
} rd[1000005];
bitset<5005> M[5005], A[5005];
void tarjan(int x){
dfn[x] = low[x] = ++in;
st[++hd] = x, vis[x] = 1;
for( int i : vec[x] ){
if(!dfn[i]){
tarjan(i);
low[x] = min(low[x], low[i]);
}
else if(vis[i]) low[x] = min(low[x], dfn[i]);
}
if(dfn[x] == low[x]){
++cnt;
scc[x] = cnt;
vis[x] = 0;
while(st[hd] != x){
scc[st[hd]] = cnt;
vis[st[hd]] = 0;
hd--;
}
hd--;
}
return;
}
int det(int n){
for( int i = 1; i <= n; i++ ) M[i].reset();
for( int i = 1; i <= n; i++ ){
for( int j = 1; j <= n; j++ ){
if(a[i][j]) M[i][j] = 1;
}
}
for( int i = 1; i <= n; i++ ){
for( int j = i; j <= n; j++ ){
if(M[j][i]){
swap(M[j], M[i]);
break;
}
}
if(!M[i][i]) return 0;
bitset<5005> T;
T.reset();
for( int j = i; j <= n; j++ ){
if(M[i][j]) T[j] = 1;
}
for( int j = i + 1; j <= n; j++ ){
if(!M[j][i]) continue;
M[j] ^= T;
}
}
return 1;
}
void top_sort(){
queue<int> q;
for( int i = 1; i <= cnt; i++ ){
if(!degree[i]) q.push(i);
}
while(!q.empty()){
int t = q.front();
q.pop();
ans[t] = 1;
for( int i = 1; i <= cnt; i++ ){
if(A[t][i]) ans[t] ^= (ans[i] & (dp[i] ^ 1));
}
sum ^= (ans[t] & (dp[t] ^ 1));
for( int i : vec[t] ){
A[i] |= A[t];
if(!--degree[i]) q.push(i);
}
}
return;
}
int main(){
// freopen("planetarian.in", "r", stdin);
// freopen("planetarian.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for( int i = 1; i <= m; i++ ){
cin >> x >> y;
vec[x].emplace_back(y);
rd[i] = {x, y};
}
for( int i = 1; i <= n; i++ ){
if(!dfn[i]) tarjan(i);
}
for( int i = 1; i <= cnt; i++ ){
int point = 0;
for( int j = 1; j <= n; j++ ){
if(scc[j] != i) continue;
bel[j] = ++point;
a[point][point] = 1;
}
for( int j = 1; j <= n; j++ ){
if(scc[j] != i) continue;
for( int k : vec[j] ){
if(scc[k] != i) continue;
a[bel[j]][bel[k]] = 1;
}
}
dp[i] = det(point);
for( int j = 1; j <= point; j++ ) memset(a[j], 0, sizeof(int) * (point + 1));
}
for( int i = 1; i <= n; i++ ) vec[i].clear();
for( int i = 1; i <= m; i++ ){
x = rd[i].x, y = rd[i].y;
if(scc[x] != scc[y]){
A[scc[x]][scc[y]] = 1;
vec[scc[y]].emplace_back(scc[x]);
degree[scc[x]]++;
}
}
top_sort();
if(sum) cout << "Mistletoe: Time to go home!" << '\n';
else cout << "Daddy: We should have a date..." << '\n';
return 0;
}
::::