題解:AT_abc352_C [ABC352C] Standing On The Shoulders

worker2011發表於2024-05-05

考場憋了很久,最後程式碼賊短……


理想狀態下,直接全排列解決問題。但是,\(1 \le n \le 2 \times 10^5\),明顯 TLE,試都不用試的。

咋最佳化呢?

其實,前面的巨人只負責“打地基”,作為“塔尖兒”的巨人有且僅有 1 個。而前面地基隨便排列,地基高度(他們的和)都不會變。所以,我們只需要列舉塔尖即可。塔尖兒定了,下面的地基高度也就定了。

然後,又是一個問題——求和!理論來講,最最暴力的方法就是一層迴圈。但是,一層迴圈時間複雜度為 \(\Theta(n)\),聯合上列舉塔尖的迴圈,時間複雜度 \(\Theta(n^2)\),又 TM 掛了……

這裡,我們可以採用一種類似字首和的思想:用一個 變數 \(sum\)(學名叫累加器) 來記錄 \(A\) 的總和,然後算去掉塔尖(\(P_i\))的時候,答案就是 \(sum - A_{P_i} + B_{P_i}\)。這個操作,時間複雜度顯然為 \(\Theta(1)\),算上迴圈為 \(\Theta(n)\),明顯可以。


賽場ACCode:

// Problem: C - Standing On The Shoulders
// Contest: AtCoder - AtCoder Beginner Contest 352
// URL: https://atcoder.jp/contests/abc352/tasks/abc352_c
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)

/*Code by Leo2011*/
#include <bits/stdc++.h>

#define log printf
#define EPS 1e-8
#define INF 0x3f3f3f3f
#define FOR(i, l, r) for (ll(i) = (l); (i) <= (r); ++(i))
#define IOS                      \
	ios::sync_with_stdio(false); \
	cin.tie(nullptr);            \
	cout.tie(nullptr);

using namespace std;

typedef __int128 i128;
typedef long long ll;
typedef pair<ll, ll> PII;

const ll N = 2e5 + 10;
ll n, mx = -INF, sum1;
PII g[N];  // pair 可以把兩個陣列懟到一塊兒,具體使用方法見 https://blog.csdn.net/sevenjoin/article/details/81937695

template <typename T>

inline T read() {
	T sum = 0, fl = 1;
	char ch = getchar();
	for (; !isdigit(ch); ch = getchar())
		if (ch == '-') fl = -1;
	for (; isdigit(ch); ch = getchar()) sum = sum * 10 + ch - '0';
	return sum * fl;
}

template <typename T>

inline void write(T x) {
	if (x < 0) {
		putchar('-'), write<T>(-x);
		return;
	}
	static T sta[35];
	ll top = 0;
	do { sta[top++] = x % 10, x /= 10; } while (x);
	while (top) putchar(sta[--top] + 48);
}

int main() {
	n = read<ll>();  // 不開 long long 見**,別問,問就是實踐出來的真知
	FOR(i, 1, n) g[i].first = read<ll>(), g[i].second = read<ll>(), sum1 += g[i].first;  // 累加器
	FOR(i, 1, n)
	mx = max(mx, sum1 - g[i].first + g[i].second);  // 上面簡單的公式
	write<ll>(mx);
	return 0;
}

AC 記錄~

理解萬歲!


先別划走,說兩件事兒。

  1. 這道題可以用貪心(同學做法),但是,貪地基高度是錯的,見https://atcoder.jp/contests/abc352/submissions/53114017,貪心需謹慎啊!

  2. 不開 long long 見**!

  3. 一張絕世好很有用的圖,可以收藏,拿走~如圖

相關文章