题解:P5954 [JSOI2013] 侦探 JYY

· · 题解

题目大意

给你一个有向无环图,一条有向边 (x,y) 代表如果 x 发生了那么 y 一定发生,求当 d 个点 x_1,x_2,\dots,x_d 发生时,有多少个点一定发生。

思路

看到这道题目就感觉跟子树有关,不难发现如果建了一个反图,那么如果 x 发生,在反图上 x 子树的点也一定发生,记录答案可以考虑用 bitset 维护,此时我们可以设 ans_i 表示 i 发生时,有哪些点一定发生。

我们再考虑一下 x 的祖先有没有可能一定发生。

先从简单的考虑,就是如果 x 在反图上只有一个父亲,那肯定直接继承 ans_{fa}。

我们再考虑一下有多个父亲的情况,样例也给出了。

我们假设已经处理了他所有父亲的 ans 值,那么我们可以发现他们 ans 中都有的点要么就是当前点 x 在反图上的子树的点,要么就是他们共同的祖先,也就说,我们可以通过他们的 ans 取交集得到这些祖先一定发生了,最后再用 ans_x 与这些一定发生的祖先的 ans 值取并集即可。

那么我们预处理的时间复杂度是 \mathcal{O}(n^2) 的,其中还有一个小于 1 的常数,我们在输入那 d 个点的时候直接将他们的 ans 取并集即可,最后按照输出格式就行了。

代码中找祖先的那一段考虑从原图中拓扑排序一下,这样写起来较为简单。

代码

其中有两个自己的样例在代码下面,没有给出那 d 个已经发生的点,需要自己补充调试,仅供参考。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stdlib.h>
#include <cstring>
#include <vector>
#include <queue>
#include <bitset>
#define int long long
#define N 1005
using namespace std;
int n,m,d,du[N];
vector<int> g[N],g2[N];
queue<int> q;
bitset<N> ans[N];
signed main(){
    // freopen("detect.in","r",stdin),freopen("detect.out","w",stdout);
    cin >> n >> m >> d;
    for (int i = 1;i <= m;i ++) {
        int u,v;
        scanf("%lld%lld",&u,&v);
        g[v].push_back(u);
        g2[u].push_back(v);
        du[u] ++;
    }
    for (int i = 1;i <= n;i ++)
        if (du[i] == 0) q.push(i);
    while(!q.empty()) {
        int t = q.front();
        q.pop();
        ans[t][t] = 1;
        for (auto i : g[t]) {
            ans[i] |= ans[t];
            if ((--du[i]) == 0) q.push(i);
        }
    }
    for (int i = 1;i <= n;i ++) du[i] = g[i].size();
    for (int i = 1;i <= n;i ++) if (du[i] == 0) q.push(i); 
    while(!q.empty()) {
        int i = q.front();
        q.pop();
        for (auto j : g2[i])
            if ((--du[j]) == 0) q.push(j);
        if (g[i].empty()) continue; 
        bitset<N> t2;
        for (int j = 1;j <= n;j ++) t2[j] = 1;
        for (auto j : g[i]) t2 = t2 & ans[j];
        for (int j = 1;j <= n;j ++)
            if (t2[j]) ans[i] |= ans[j]; 
    }
    bitset<N> t;
    for (int i = 1;i <= d;i ++){
        int x;
        scanf("%lld",&x);
        t |= ans[x];
    }
    for (int i = 1;i <= n;i ++) if (t[i]) printf("%lld ",i);
    return 0;
}
/*
13 17 1
1 2
1 3
2 4
2 5
5 6
6 7
6 8
6 9
7 10
8 10
8 11
9 11 11 12
10 12
3 5
4 6
13 4

5 4 1
1 2
2 3
3 4
5 3
*/