动态规划基础题(第4题): 此累积和非累积和

碎碎念

  • 这道题稍有些水,比赛时遇到这种题就开心了。

标签

  • 累积和、排序

合集

  • 动态规划、累积和、排序

题目地址

C - Exception Handling

  • https://atcoder.jp/contests/abc134/tasks/abc134_c?lang=en

问题描述

You are given a sequence of length N: A 1 _1 1, A 2 _2 2, …, A N _N N. For each integer i between 1 and N (inclusive), answer the following question:

  • Find the maximum value among the N-1 elements other than A i _i i in the sequence.

Constraints

  • 2≤N≤200000
  • 1 ≤ \leq A i _i i ≤ \leq 200000
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A1
:
AN

Output

Print N lines. The i-th line (1≤iN) should contain the maximum value among the N−1 elements other than A i _i i in the sequence.


Sample Input 1

3
1
4
3

Sample Output 1

4
3
4
  • The maximum value among the two elements other than A 1 _1 1, that is, A 2 _2 2 = 4 and A 3 _3 3 = 3, is 4.
  • The maximum value among the two elements other than A 2 _2 2, that is, A 1 _1 1 = 1 and A 3 _3 3 = 3, is 3.
  • The maximum value among the two elements other than A 3 _3 3, that is, A 1 _1 1 = 1 and A 2 _2 2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5

题解

小码匠

void coder_solution() {
    // 提升cin、cout效率
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    vector<int> a(n);
    vector<int> dp(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        dp[i] = a[i];
    }
    
    sort(dp.begin(), dp.end());
    
    for (int i = 0; i < n; ++i) {
        if(a[i] == dp[n - 1]) {
            cout << dp[n - 2] << endl;
        } else {
            cout << dp[n - 1] << endl;
        }
    }
}

参考题解

  • 累积和思路
    • 从开头和结尾构造了两个数组
      • lft [i]: = 从 A [0] 到 A [i] 的最大值
      • rht [i]: = 从 A [i] 到 A [N-1] 的最大值
      • 如果这样做,第 i 个以外的最大值将是 max (lft [i -1], rht [i + 1])
int N, A[201010];
int lft[201010], rht[201010];
//---------------------------------------------------------------------------------------------------
void _main() {
	cin >> N;
	rep(i, 0, N) cin >> A[i];
 
	rep(i, 0, N) lft[i] = A[i];
	rep(i, 1, N) chmax(lft[i], lft[i - 1]);
 
	rep(i, 0, N) rht[i] = A[i];
	rrep(i, N - 2, 0) chmax(rht[i], rht[i + 1]);
 
	rep(i, 0, N) {
		int ans = -1;
		if (0 < i) chmax(ans, lft[i - 1]);
		if (i + 1 < N) chmax(ans, rht[i + 1]);
		printf("%d\n", ans);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小码匠和老码农

喜欢作者

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值