P1115 最大子段和&P1719 最大加权矩形
2024-09-03 04:06:31
这两个题本质是一个亚子,所以放一起啦
DPDPDPDPDPDPDPDP
P1115 最大子段和
题解
因为题目要求的是一段连续的区间,所以前缀和搞暴力???
我们设置数组 f[ i ] 表示以 a[ i ] 结尾的最大连续子段和
那么转移???
1.接着上一段,继续构成一段连续的子段 continue the old life
2.自成一段 和过去 say goodbye
转移方程:
ans记录最大值就好啦
代码
#include<bits/stdc++.h> using namespace std; inline int read()
{
int ans=;
char last=' ',ch=getchar();
while(ch<''||ch>'') last=ch,ch=getchar();
while(ch>=''&&ch<='') ans=ans*+ch-'',ch=getchar();
if(last=='-') ans=-ans;
return ans;
} const int maxn=2e5+;
int n,ans;
int a[maxn];
int f[maxn]; int main()
{
n=read();
for(int i=;i<=n;i++)
a[i]=read();
f[]=;f[]=a[];
ans=a[];
for(int i=;i<=n;i++)
{
f[i]=max(f[i-]+a[i],a[i]);
ans=max(ans,f[i]);
}
printf("%d\n",ans); return ;
}
P1719 最大加权矩形
题解
其实这个题就是上一个的变式,我们只需要把本题的二维转变成一维就好啦!
考虑枚举子矩阵的上下界
确定了上下界,就缩成了一维,此时只需要算 “该行” ,的最大 f[ ] 就好啦!
解释一下数组:
a[ i ][ j ] :读入给出的矩阵
sum[ i ][ j ] :第 j 列,前 i 行的前缀和
其实这里的 就相当于上一个题的
代码
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue> using namespace std; inline int read()
{
int ans=;
char last=' ',ch=getchar();
while(ch<''||ch>'') last=ch,ch=getchar();
while(ch>=''&&ch<='') ans=ans*+ch-'',ch=getchar();
if(last=='-') ans=-ans;
return ans;
} const int maxn=;
int n,ans=-;
int a[maxn][maxn],sum[maxn][maxn],f[maxn]; int main()
{
n=read();
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
a[i][j]=read(),sum[i][j]=sum[i-][j]+a[i][j]; for(int i=;i<=n;i++)
for(int j=i;j<=n;j++) //枚举上下界 i~j
{
memset(f,,sizeof(f));
for(int k=;k<=n;k++) //DP
f[k]=max(f[k-]+(sum[j][k]-sum[i-][k]),(sum[j][k]-sum[i-][k])),
ans=max(ans,f[k]);
} printf("%d",ans);
return ;
}
最新文章
- Easyui datagrid加载本地Json数据,CGI数据
- andriod studio
- 实现jquery.ajax及原生的XMLHttpRequest跨域调用WCF服务的方法
- WPF Window 服务安装
- 让ecshop用户登录评价以可择匿名评价
- RAC 之 RMAN 备份
- [Angular 2] @ViewChild to access Child component&#39;s method
- android ListView用法介绍
- PNG图片小结
- python binary lib on win/各种python库的二进制包
- React.js终探(七)(完)
- Hadoop YARN ERROR 1/1 local-dirs are bad *, 1/1 log-dirs are bad *
- 创建mongodb副本集操作实例
- B+树和B-树的区别
- redis+Keepalived主从热备切换实例
- idea打包含第三方依赖的jar包
- js计算器---转
- 07装饰模式Decorator
- 在 .NET Framework Data Provider for Microsoft SQL Server Compact 3.5 中发生错误
- 集合02_Queue