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;
}
相关推荐
GalaxyPokemon31 分钟前
归并排序:分治思想的高效排序
数据结构·算法·排序算法
ThreeYear_s33 分钟前
基于FPGA的PID算法学习———实现PI比例控制算法
学习·算法·fpga开发
Coding小公仔3 小时前
LeetCode 240 搜索二维矩阵 II
算法·leetcode·矩阵
C++chaofan3 小时前
74. 搜索二维矩阵
java·算法·leetcode·矩阵
Studying 开龙wu4 小时前
机器学习监督学习实战五:六种算法对声呐回波信号进行分类
学习·算法·机器学习
Mi Manchi264 小时前
力扣热题100之二叉树的层序遍历
python·算法·leetcode
wu~9704 小时前
leetcode:42. 接雨水(秒变简单题)
算法·leetcode·职场和发展
zhurui_xiaozhuzaizai5 小时前
模型训练-关于token【低概率token, 高熵token】
人工智能·算法·自然语言处理
ThreeYear_s5 小时前
基于FPGA的PID算法学习———实现PID比例控制算法
学习·算法·fpga开发