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;
}
相关推荐
We་ct11 分钟前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
王老师青少年编程4 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮5 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说5 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wuweijianlove6 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
leoufung6 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了6 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL6 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
谭欣辰6 小时前
C++ 排列组合完整指南
开发语言·c++·算法
代码中介商7 小时前
银行管理系统的业务血肉 —— 流程、状态机、输入校验与持久化(下篇)
c语言·算法