C. Theofanis‘ Nightmare

原题链接 :

Problem - 1903C - Codeforces

思路 :

创建一个后缀和数组 , 然后把所有后缀和>0的加入到答案中,注意,整个数组的和一定要加入答案中 ;

代码

java :

复制代码
package sf;

import java.util.Scanner;
import java.util.* ;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in) ;
        int t = sc.nextInt() ;
        StringBuilder sb = new StringBuilder() ;
        while(t--!=0){
            int n = sc.nextInt() ;
            long[] a = new long[n + 1] ;
            long[] ed = new long[n+1] ;
            for(int i=1;i<=n;i++){
                a[i] = sc.nextInt() ;
            }
            ed[n] = a[n] ;
            for(int i=n-1;i>=1;i--){
                ed[i] = ed[i+1]+a[i] ;
            }      
            long ans = ed[1] ;
            for(int i=2;i<=n;i++){
                if(ed[i]>0){
                    ans += ed[i] ;
                }
            }
            sb.append(ans).append('\n') ;
        }
        System.out.println(sb);
        sc.close() ;
    }
}

C++

复制代码
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
using namespace std;
typedef long long LL;
const int N = 2e5 + 10 ;

LL a[N] ,ed[N] ;

inline void solve(){
    int n ; cin >> n ;
    for(int i=1;i<=n;i++) cin >> a[i] ;
    ed[n] = a[n] ;
    for(int i=n-1;i>=1;i--) ed[i] = ed[i+1]+a[i] ;
    LL ans = ed[1] ;
    for(int i=2;i<=n;i++){
        if(ed[i]>0){
            ans += ed[i] ;
        }
    }
    cout << ans << endl ;
}
 
signed main(){
    IOS
    int _ = 1;
    cin >> _;
    while(_ --) solve();
    return 0;
}
相关推荐
半桔1 小时前
【STL源码剖析】二叉世界的平衡:从BST 到 AVL-tree 和 RB-tree 的插入逻辑
java·数据结构·c++·算法·set·map
塔中妖2 小时前
【华为OD】分割数组的最大差值
数据结构·算法·华为od
weixin_307779132 小时前
最小曲面问题的欧拉-拉格朗日方程 / 曲面极值问题的变分法推导
算法
RTC老炮2 小时前
webrtc弱网-AlrDetector类源码分析与算法原理
服务器·网络·算法·php·webrtc
孤廖2 小时前
【算法磨剑:用 C++ 思考的艺术・Dijkstra 实战】弱化版 vs 标准版模板,洛谷 P3371/P4779 双题精讲
java·开发语言·c++·程序人生·算法·贪心算法·启发式算法
sali-tec2 小时前
C# 基于halcon的视觉工作流-章33-矩状测量
开发语言·人工智能·算法·计算机视觉·c#
songx_993 小时前
leetcode29( 有效的括号)
java·数据结构·算法·leetcode
于樱花森上飞舞3 小时前
【java】常见排序算法详解
java·算法·排序算法
GawynKing3 小时前
图论3 图的遍历
算法·深度优先
东方芷兰5 小时前
Leetcode 刷题记录 21 —— 技巧
java·算法·leetcode·职场和发展·github·idea