当前位置:网站首页>PAT1007
PAT1007
2022-08-09 11:09:00 【AlanLiu6】
暴力解法
https://pintia.cn/problem-sets/994805342720868352/problems/994805514284679168
#include<cstdio>
int num[10005];
int main()
{
int k;
scanf("%d",&k);
for(int i = 0;i < k;i++)
{
scanf("%d",&num[i]);
}
int sum=0,first=0,last=k-1;
for(int i = 0;i < k;i++)
{
int tSum=0;
for(int j = i;j < k;j++)
{
tSum += num[j];
if(tSum > sum ||(tSum == sum &&tSum == 0))
{
first = i;
last = j;
sum = tSum;
}
}
}
printf("%d %d %d\n",sum,num[first],num[last]);
return 0;
}
非暴力写法, 来源
#include <iostream>
#define mm 10001
using namespace std;
int maxsequence3(int a[], int len);
int start=0;
int last=0;
int main()
{
int M,arr[mm]={0};
int max=0;
cin>>M;
for(int i=0;i<M;i++)
cin>>arr[i];
int j=0;
while(arr[j]<0&&j<M)
j++;
if(j==M)
{
cout<<"0 "<<arr[0]<<" "<<arr[M-1];
return 0;
}
int sum=maxsequence3(arr, M);
cout<<sum<<' '<<arr[start]<<' '<<arr[last];
return 0;
}
int maxsequence3(int a[], int len)
{
int maxsum, maxhere,temp_start,temp_last;
temp_start=0;
temp_last=0;
maxsum=a[0];
maxhere=a[0]; //初始化最大和为a【0】
for (int i=1;i<len;i++)
{
if (maxhere<= 0)
{
maxhere=a[i]; //如果前面位置最大连续子序列和小于等于0,则以当前位置i结尾的最大连续子序列和为a[i]
temp_start=i;
}
else
{
maxhere+=a[i]; //如果前面位置最大连续子序列和大于0,则以当前位置i结尾的最大连续子序列和为它们两者之和
temp_last=i;
}
if (maxhere>maxsum)
{
maxsum=maxhere; //更新最大连续子序列和
start=temp_start;
last=temp_last;
}
}
if(start>last)
last=start;//避免出现下面状况start不断更新,而last保持第一个不变,所以额外添加这个if判断语句,如果输入序列为 -1 -2 -3 0 -4,这个if判断就是必须的
return maxsum;
}
边栏推荐
- ∘(空心的点乘)的数学含义
- Qt 国际化翻译
- Preparation for gold three silver four: how to successfully get an Ali offer (experience + interview questions + how to prepare)
- Netscope: Online visualization tool for neural network structures
- 【C language】动态数组的创建和使用
- margin出bug---margin失效
- Solve 1. tensorflow runs using CPU but not GPU 2. GPU version number in tensorflow environment 3. Correspondence between tensorflow and cuda and cudnn versions 4. Check cuda and cudnn versions
- x86 Exception Handling and Interrupt Mechanism (3) Interrupt Handling Process
- Quartz的理解
- es6对象迭代器iterator
猜你喜欢
MATLAB中如何把cftool拟合的函数输出到命令行(解决如何导出拟合后的曲线数据)
Getting Started with MNIST Machine Learning
性能测试(03)-JDBC Request
UNIX Philosophy
∘(空心的点乘)的数学含义
Preparation for gold three silver four: how to successfully get an Ali offer (experience + interview questions + how to prepare)
电磁场与电磁波-场论基础
七夕?程序员不存在的~
c语言函数的递归调用(汉诺塔问题,楼梯递归问题等)
UNIX哲学
随机推荐
无刷无霍尔BLCD电机控制
The use of signal function (signal) in C language
在线编译matlab,亲测好用
threejs+shader 曲线点运动,飞线运动
golang 三种指针类型具体类型的指针、unsafe.Pointer、uintptr作用
uni-app 自带的picker封装一个日期-时间选择器
ECCV 2022 Oral | CCPL: 一种通用的关联性保留损失函数实现通用风格迁移
Qt读写.ini配置文件
程序员的专属浪漫——用3D Engine 5分钟实现烟花绽放效果
【VIBE: Video Inference for Human Body Pose and Shape Estimation】论文阅读
ACM最长不下降子序列问题
C语言统计不同单词数
最长回文子串
FreeRTOS列表和列表项源码分析
依赖注入(Dependency Injection)框架是如何实现的
Missing URI template variable ‘employeeNumber‘ for method parameter of type String
focusablejs
golang源代码阅读,sync系列-Cond
vite的原理,手写vite
Jmeter BeanShell post processor