当前位置: 首页 > news >正文

PAT甲级1007 Maximum Subsequence Sum

 题目地址:

编程题 - PAT (Advanced Level) Practice (pintia.cn)

介绍

前缀和

Given a sequence of K integers { N1​, N2​, ..., NK​ }. A continuous subsequence is defined to be { Ni​, Ni+1​, ..., Nj​ } where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long  
#define ull unsigned long longvoid solve() {int n;cin>>n;ll num_add[10001];ll max1=INT_MIN;int begin,end;ll sum=0;int i,j;int key=1;for(i=0;i<=n-1;i++){cin>>j;if(j>=0){key=0;}sum+=j;num_add[i]=sum;}max1=num_add[0];begin=0;end=0;if(key){cout<<0<<" "<<num_add[0]<<" "<<num_add[n-1]-num_add[n-2];;return ;}for(i=0;i<=n-1;i++){for(j=i+1;j<=n-1;j++){if(num_add[j]-num_add[i]>max1){max1=num_add[j]-num_add[i];begin=i+1;end=j;}}}if(max1==num_add[0]){cout<<max1<<" "<<num_add[begin]<<" "<<num_add[end];}elsecout<<max1<<" "<<num_add[begin]-num_add[begin-1]<<" "<<num_add[end]-num_add[end-1];
} signed main() {ll t = 1; // std::cin >> t;while (t--) {solve();}
}


http://www.mrgr.cn/news/49271.html

相关文章:

  • 24/10/13 算法笔记 批量规范化
  • stm32单片机个人学习笔记9(TIM输入捕获)
  • node简单实现读取文件内容
  • 第十五届蓝桥杯C/C++学B组(解)
  • C语言实现输出空心数字金字塔
  • Vue——Uniapp回到顶部悬浮按钮
  • 计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-13
  • 【gRPC】gRPC简单使用 protocol
  • GPT联网分析到底有多强?实测效果告诉你答案!
  • Mybatis(看这一篇就够了)
  • 可变参数列表详解
  • Jira 效率革命:从团队抱怨到交口称赞 | 专家实战分享三大秘技,让团队爱上效率工具
  • windows环境在git bash中配置jdk和maven
  • 责任链模式(C++)
  • 桥接模式(C++)
  • 架构设计笔记-12-信息系统架构设计理论与实践
  • Vue学习笔记
  • Claude 账号被封怎么办?被封的原因有哪些?国内不怕封号的方法
  • vue3集成electron
  • 如何在UE5中创建加载屏幕(开场动画)?