题解:P1001 A+B Problem

· · 题解

简单题,不知道大家为什么做得那么麻烦。

引用一句忘了在哪里看到的话:遇到不明二元关系就建图。加法似乎没有什么特别好的性质,所以我们建两个结点 u 和 v,然后令 u 的权值为 a,v 的权值为 b,接着让它们之间建一条双向边,不难发现这个图是一个强连通图。

然后这就是缩点板子题了,我们跑一个 Tarjan 然后拓扑排序时 dp 一下即可,时间复杂度 O(1),吊打大多数带 \log 甚至是根号的题解。

注意输入的数可能是负数,所以 dp 时不能直接取 std::max 而是要相加。

#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<cassert>

constexpr int N = 2 + 5;

int a, b, n = 2, w[N]; std::vector<int> G[N], nG[N];
int dfn[N], low[N], blg[N], tot = 0;
std::stack<int> st; bool in_st[N], pred[N];
int scct = 0, wsum[N]; std::vector<int> scc[N];
std::set<int> added[N]; int in[N], dp[N];

void tarjan(int u) {
    dfn[u] = low[u] = ++tot;
    st.push(u); in_st[u] = true;
    for(const auto& v : G[u]) {
        if(!dfn[v]) {
            tarjan(v); low[u] = std::min(low[u], low[v]);
        } else {
            if(in_st[v]) low[u] = std::min(low[u], low[v]);
        }
    }
    if(dfn[u] == low[u]) {
        std::vector<int> vec; vec.push_back(u);
        while(st.top() != u) {
            blg[st.top()] = scct + 1;
            vec.push_back(st.top());
            wsum[scct + 1] += w[st.top()];
            in_st[st.top()] = false; st.pop(); 
        }
        wsum[scct + 1] += w[u];
        in_st[u] = false; st.pop();
        blg[u] = scct + 1; scc[++scct] = vec;
    }
}

inline int topo() {
    std::queue<int> q; int ret = 0;
    for(int u = 1; u <= scct; ++u) {
        if(!in[u]) {
            q.push(u); dp[u] = wsum[u];
        }
    }
    while(!q.empty()) {
        int u = q.front(); q.pop();
        for(const auto& v : nG[u]) {
            dp[v] = dp[u] + wsum[v];
            ret += dp[v]; if(!(--in[v])) q.push(v);
        }
    }
    return ret;
}

int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(0), std::cout.tie(0);

    std::cin >> w[1] >> w[2]; G[1].push_back(2);
    for(int u = 1; u <= n; ++u) {
        if(!dfn[u]) tarjan(u);
    }
    for(int u = 1; u <= n; ++u) {
        for(const auto& v : G[u]) {
            int bu = blg[u], bv = blg[v];
            if(bu == bv || added[bu].count(bv)) continue;
            added[bu].insert(bv); nG[bu].push_back(bv); ++in[bv];
        }
    }
    // std::cerr << wsum[1] << "\n";
    std::cout << topo() << "\n";

    return 0;
}