跳到正文

题解

题解:P5954 [JSOI2013] 侦探 JYY

high_sky约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年8月18日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 4 分钟
获赞
1
题目
P5954

版本

  1. v1当前

题目大意

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

思路

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

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

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

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

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

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

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

代码

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

C++
#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
*/
原文