跳到正文

个人记录

HDU - 1827题解

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟

版本

  1. v1当前

思路

一眼就可以知道这就是缩点的模型,所以先缩点。

然后要求电话费要最小,所以对于每个 sccscc 只打给其中要求电话费最小的人即可。

注意: 此题可能有孤立点。

代码

C++
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 2e5 + 10;

int dfn[N], low[N], p[N], id[N], a[N], scc_cnt, tot, ans2, ans, t[N];
vector<int> v[N];
stack<int> st;

void tarjan(int x) {
    dfn[x] = low[x] = ++tot;
    st.push(x);

    for (int y : v[x]) {
        if (!dfn[y]) {
            tarjan(y);
            low[x] = min(low[x], low[y]);
        } else if (!p[y]) {
            low[x] = min(low[x], dfn[y]);
        }
    }

    if (low[x] == dfn[x]) {
        scc_cnt++;
        int tmp = INT_MAX;
        while (1) {
            int o = st.top();
            st.pop();
            p[o] = scc_cnt;
            tmp = min(tmp, a[o]);
            if (o == x) break;
        }
        t[scc_cnt] = tmp;
    }
}

void dfs(int n) {
    tot = scc_cnt = ans2 = ans = 0;
    memset(dfn, 0, sizeof(int) * (n + 1));
    memset(low, 0, sizeof(int) * (n + 1));
    memset(p, 0, sizeof(int) * (n + 1));
    memset(id, 0, sizeof(int) * (n + 1));
    for (int i = 1; i <= n; i++) {
        if (!dfn[i]) {
            tarjan(i);
        }
    }
    for (int x = 1; x <= n; x++) {
        for (int y : v[x]) {
            if (p[x] != p[y]) {
                id[p[y]]++;
            }
        }
    }
    for (int i = 1; i <= scc_cnt; i++) {
        if (id[i] == 0) {
            ans++;
            ans2 += t[i];
        }
    }
}

int main() {
    int n, m, x, y;
    while (~scanf("%d%d", &n, &m)) {
        for (int i = 1; i <= n; i++) {
            v[i].clear();
            scanf("%d", &a[i]);
        }
        for (int i = 0; i < m; i++) {
            scanf("%d%d", &x, &y);
            v[x].push_back(y);
        }
        dfs(n);
        cout << ans << ' ' << ans2 << '\n';
    }
    return 0;
}
原文