题解:AT_abc454_c [ABC454C] Straw Millionaire

· · 题解

图论题

建模,有1-N编号的节点,第i个朋友就就在A_i与B_i之间建一条单向边,最后用BFS搜索最多有多少个点是可从1出发到达的。

代码很简单。

#include <bits/stdc++.h>
using namespace std;
const int N = 300010;
int n, m, ans;
bool vis[N];
vector<int> p[N];
queue<int> q;
void bfs(){
    int u, to;
    q.push(1);
    while (!q.empty()){
        u = q.front();
        q.pop();
        if (vis[u]) continue;
        vis[u] = 1;
        for (int i = 0; i < p[u].size(); i++){
            to = p[u][i];
            if (!vis[to]){
                q.push(to);
            }
        }
    }
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    for (int i = 1, u, v; i <= m; i++){
        cin >> u >> v;
        p[u].push_back(v);
    } 
    bfs();
    for (int i = 1; i <= n; i++){
        if (vis[i]) ans++;
    }
    cout << ans;
    return 0;
}

::::warning[提示] Atcoder better的翻译有点问题,翻译出来还以为是求最长路,经队友提醒才发现是BFS。 ::::