栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

可达性统计

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

可达性统计

可达性统计

[link](AcWing 164. 可达性统计 - AcWing)

题意

给定一张 N N N个点 M M M 条边的有向无环图,分别统计从每个点出发能够到达的点的数量。

题解

每一个点能到的所有的点等价于这个点的直接后继节点能到的点的并集。因为是有向无环图所以拓扑排序以后,当前的拓扑序的某个点u的所有的出边边一定是指向拓扑序后面的点,因此可以倒着遍历这个拓扑序来维护,因为数据范围 1 ≤ N , M ≤ 30000 1le N, M le 30000 1≤N,M≤30000,最坏的情况下是会成为一条链,每个点都会和后面 x − 1 x-1 x−1个点,产生交集,这样就要开一个 n 2 n^2 n2的数组来存, 1 0 6 10^6 106的 i n t int int大概需要 4 M B 4MB 4MB,所以会超内存,考虑用二进制来优化,C++自带bitset,可以用bitset这样就可以降低空间复杂度。

Code

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include 
#include 
#include  
#include 
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair PII;
typedef pair PDD;
typedef unsigned long long ULL;
const int N = 1e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
    e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
bitset f[N];
int q[N];
int d[N];
void topsort() {
    int hh = 0, tt = -1;
    for (int i = 1; i <= n; i ++ ) if (!d[i])  q[++ tt] = i;
    while (hh <= tt) {
        int t = q[hh ++];
        for (int i = h[t]; ~i; i = ne[i]) {
            int j = e[i];
            if (-- d[j] == 0) q[++ tt] = j;            
        }
    }
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while (m --) {
        int a, b;
        cin >> a >> b;
        add(a, b);
        d[b] ++;
    }
    topsort();
    for (int i = n - 1; ~i; i -- ) {
       int j = q[i];
        f[j][j] = 1;
        for (int k = h[j]; ~k; k = ne[k])  
            f[j] |= f[e[k]];
    }
    for (int i = 1; i <= n; i ++ ) cout << f[i].count() << endl;
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/291134.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号