跳到正文

个人记录

ABC245F

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

文章信息

发布
2023年4月21日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 4 分钟

版本

  1. v1当前

ABC245F

拓扑图 + 反向建图

这个题目就是启发了一件事情那就是反向建图,这个东西真的很奇特。

解题思路

  1. 这个题目的意思就是说,有哪些点可以走到环上去。

  2. 看到下面这个图,左边是正常建图,右边是反向图,我们发现,左边的图链子都是符合要求的,我们反向建图之后发现,就是右边的图,

  1. 基于此我们受到启发,可以考虑反向建图。然后跑拓扑序,如果出现了在拓扑序中的点,那说明在原图中这个点是向离圈方向去的,因此肯定是不会走到圈子上去的。那么这个题目就做出来了。
C++
#include <set>
#include <map>
#include <queue>
#include <cmath>
#include <cstring>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>

// #define int LL
#define endl '\n'
#define double long double
#define big_heap(T) priority_queue<T>
#define small_heap(T) priority_queue<T, vector<T>, greater<>>

using namespace std;

typedef long long LL;
typedef pair<LL, LL> PLL;
typedef pair<int, LL> PIL;
typedef pair<LL, int> PLI;
typedef pair<int, int> PII;
typedef unsigned long long ULL;
typedef pair<double, double> PDD;

const double EXP = 1e-8;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const LL LNF = 0x3f3f3f3f3f3f3f3f;
void IOS() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
}

const int N = 200010;

int res;
int d[N];
int n, m;
vector<int> g[N];

void solve() {
    cin >> n >> m;
    while (m -- ) {
        int a, b;
        cin >> a >> b;
        g[b].push_back(a);
        d[a] ++ ;
    }
    queue<int> q;
    for (int i = 1; i <= n; i ++ ) {
        if (!d[i]) q.push(i);
    }
    res = n;
    while (!q.empty()) {
        auto t = q.front();
        q.pop();
        res -- ;
        for (int j : g[t]) {
            if ( -- d[j] == 0) q.push(j);
        }
    }
    cout << res << endl;
}

signed main() {
    IOS();
    int T = 1;
//    cin >> T;
    while (T--) {
        solve();
    }
    return 0;
}
原文