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;
}
相关推荐
不穿格子的程序员7 分钟前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng1 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng1 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
2301_800399721 小时前
stm32 printf重定向到USART
java·stm32·算法
顾安r2 小时前
11.15 脚本算法 加密网页
服务器·算法·flask·html·同态加密
前端小L2 小时前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿2 小时前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
元亓亓亓3 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
2401_841495643 小时前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——寻找数组的中心下标
算法·leetcode·职场和发展·结构与算法