4.2沟里学姐的残忍
就是找一定范围内,和最大的区间
解题,一种用区间最值的方法,先开一个前缀和数组,然后从每一个点开始找后面一定范围内的区间最大值,然后比较找出最大的就好了
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <iomanip>
#include<cmath>
#include<float.h>
#include<string.h>
#include<algorithm>
#define sf scanf
#define scf(x) scanf("%d",&x)
#define scff(x,y) scanf("%d%d",&x,&y)
#define pf printf
#define prf(x) printf("%d\n",x)
#define mm(x,b) memset((x),(b),sizeof(x))
#include<vector>
#include<queue>
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
typedef long long ll;
const ll mod=1e9+100;
const double eps=1e-8;
using namespace std;
const double pi=acos(-1.0);
const int inf=0xfffffff;
const int N=1e5+7;
int a[N],sum[N];
int dpmax[N][20];
void first(int n)
{
mm(dpmax,0);
rep(i,1,n+1)
{
dpmax[i][0]=sum[i];
}
for(int j=1;(1<<j)<=n;j++)
{
for(int i=1;i+(1<<j)-1<=n;i++)
{
dpmax[i][j]=max(dpmax[i][j-1],dpmax[i+(1<<(j-1))][j-1]);
}
}
}
int fmax(int l,int r)
{
int x=0;
while(l-1+(1<<x)<=r) x++;
x--;
return max(dpmax[l][x],dpmax[r-(1<<x)+1][x]);
}
int main()
{
// freopen("input.txt","r",stdin);
int n,k;int maxx=-inf,l,r;
sum[0]=0;
scff(n,k);
rep(i,1,n+1)
{
scf(a[i]);
sum[i]=sum[i-1]+a[i];
}
first(n);
int right;
rep(i,1,n)
{
if(n<i+k-1)
right=n;
else
right=i+k-1;
if(fmax(i,right)-sum[i-1]>maxx)
{
maxx=fmax(i,right)-sum[i-1];
l=i;
}
}
if(maxx<a[n])
{
pf("%d %d %d",maxx,n,n);
return 0;
}
rep(i,l,n+1)
{
if(sum[i]-sum[l-1]==maxx)
{
r=i;
break;
}
}
pf("%d %d %d",maxx,l,r);
return 0;
}
第二种蛮看一下
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <iomanip>
#include<cmath>
#include<float.h>
#include<string.h>
#include<algorithm>
#define sf scanf
#define scf(x) scanf("%d",&x)
#define scff(x,y) scanf("%d%d",&x,&y)
#define pf printf
#define prf(x) printf("%d\n",x)
#define mm(x,b) memset((x),(b),sizeof(x))
#include<vector>
#include<queue>
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
typedef long long ll;
const ll mod=1e9+100;
const double eps=1e-8;
using namespace std;
const double pi=acos(-1.0);
const int inf=0xfffffff;
const int N=1e5+7;
struct node
{
int sum;
int id;
bool friend operator < (node a,node b)
{
if(a.sum==b.sum) return a.id>b.id;
return a.sum>b.sum;
}
}a[N];
priority_queue<node> v;
int main()
{
int n,k,x,maxx,l=1,r=1;
a[0].sum=0;
a[0].id=0;
v.push(a[0]);
scff(n,k);
rep(i,1,n+1)
{
scf(x);
a[i].id=i;
a[i].sum+=a[i-1].sum+x;
}
maxx=a[1].sum;
v.push(a[1]);
node t;
rep(i,2,n+1)
{
while(!v.empty())
{
t=v.top();
if(i-t.id<=k) break;
else v.pop();
}
if(a[i].sum-t.sum>maxx)
{
maxx=a[i].sum-t.sum;
l=t.id+1;
r=a[i].id;
}
v.push(a[i]);
}
pf("%d %d %d\n",maxx,l,r);
}