51Nod 1049最大子段和 | 模板
2024-08-26 01:31:53
Input示例
6
-2
11
-4
13
-5
-2
Output示例
20
1.最大子段和模板
#include "bits/stdc++.h"
using namespace std;
#define rep(i, s, n) for(int i=s;i<n;i++)
#define LL long long
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define E 2.71828
#define MOD 1000000007
#define N 50010
LL a[N];
LL b[N];
int main()
{
LL max1 = ;
int n;
while(~scanf("%d",&n))
{
bool f=;
rep(i,,n){
scanf("%lld",&a[i]);
}
memset(b,,n+);
max1=-INF;
rep(i,,n)
{
if(b[i-]>)
{
b[i] = b[i-]+a[i];
}else{
b[i] = a[i];
}
if(b[i]>max1)
max1 = b[i];
}
if(max1<)
max1=;
cout<<max1<<endl;
}
return ;
}
2.
预处理:前缀和
last:上一个正数的位置
dp[i]表示这个子段最后一个是i的最大和
状态转移:
如果前一个是非负数,dp[i]=dp[i-1]+a[i]
否则,dp[i]=max(a[i],dp[last]+sum[i]-dp[last])
原理跟最大字段和一样
#include "bits/stdc++.h"
using namespace std;
#define rep(i, s, n) for(int i=s;i<n;i++)
#define LL long long
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define E 2.71828
#define MOD 1000000007
#define N 50010
int n;
long long a[N],dp[N],sum[N];
int main()
{
while(~scanf("%d",&n)){
int last=;
rep(i,,n+) cin>>a[i];
rep(i,,n+) sum[i]=sum[i-]+a[i];
rep(i,,n+)
{
if(a[i-]>=)
dp[i]=dp[i-]+a[i],last=i;
else
dp[i]=max(a[i],dp[last]+sum[i]-sum[last]);
}
LL ans=;
rep(i,,n+)
ans=max(ans,dp[i]);
printf("%lld",ans);
}
return ;
}
最新文章
- Myeclipse下的struts2.3.8 配置 保证绝对好用
- 向苹果App Store提交新应用的图文教程(转)
- NSLog 自定义 屏蔽
- mysql学习笔记 第六天
- Shell命令_case
- 使用宏批量将多个csv文件转成excel文件
- js 去掉浏览器右击默认事件
- Purchase Document Open Interface(PDOI)
- pyqt lineedit右边显示按钮效果
- NET基础课--JIT编译器如何工作1
- Microsoft dynamic sdk中join应该注意的问题.
- 网站SEO优化问答精选
- 统一修改表单参数(表单提交的空字符串统一转null)
- 依赖注入[2]: 基于IoC的设计模式
- Roomblock: a Platform for Learning ROS Navigation With Roomba, Raspberry Pi and RPLIDAR(转)
- 20175208 张家华 MyOD
- AOSP android 源码下载
- the network could not establish the connection
- WCF绑定netTcpBinding寄宿到控制台应用程序
- numpy 中的 broadcasting 理解
热门文章
- 一道java笔试题
- python中spilt()函数和os.path.spilt()函数区别
- POJ 1739 Tony&#39;s Tour(插头DP)
- NFS服务搭建使用
- 解决打包遇到的_mssql问题
- (转)Linux NUMA引发的性能问题
- 安装django 提示ImportError: No module named setuptools
- PHP给图片添加图片水印
- [OS] 操作系统基本类型
- Windows7系统目录迁移:Users,Progr…