跳到正文

题解

题解:P1001 A+B Problem

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

文章信息

发布
2025年5月10日
收录
2026年5月27日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
12
题目
P1001

版本

  1. v1当前

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

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

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

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

C++
#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;
}
原文
存档评论23 条抓取于