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;
}
相关推荐
专注仿真4 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
码爸5 小时前
支持向量机介绍与示例
算法·机器学习·支持向量机
怕浪猫5 小时前
2028编程圈很火的10个Skills
算法·面试·github
Nil2089 小时前
leetcode 198打家劫舍
算法·leetcode·职场和发展
Shaoshing10 小时前
前缀和与差分
java·数据结构·算法·前缀和·差分
loulanyue_10 小时前
构建房产认知决策智能:Harness底座与AI自进化的技术实践——读贝壳首席算法科学家尹俊希2026云栖专场演讲
人工智能·算法
碧海银沙音频科技研究院10 小时前
基于炬芯ATS录音卡BLE控制协议
人工智能·嵌入式硬件·算法·语音识别
suhan11 小时前
【数据结构】三、栈和队列:6.链队列、双端队列、队列的应用(树的层次遍历、广度优先BFS、先来先服务FCFS)
数据结构·后端·算法
姜鱼问生11 小时前
Docker Volume 备份与恢复实战:不停机迁移数据
后端·算法·架构
suhan11 小时前
【数据结构】三、栈和队列:5.顺序队列(循环队列)(初始化,判空判满,入队,出队,实例)
数据结构·后端·算法