先来一个按照中间值进行分治的例题:
例题1 :最大连续和
C. 最大子段和
NN个整数组成的序列 a[1],a[2],a[3],…,a[n],求该序列如 a[i]+a[i+1]+…+a[j]的连续子段和的最大值。当所给的整数均为负数时和为 0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为 20。
Input
第 11 行:整数序列的长度 NN (2≤N≤50000)(2≤N≤50000)
第 2−N+12−N+1 行:NN 个整数 (−109≤A[i]≤109)(−109≤A[i]≤109)
Output
输出最大子段和
Example
6
-2
11
-4
13
-5
-2
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
C. Creative Snap
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
burn the current base. If it contains no avenger in it, it takes AA amount of power, otherwise it takes his B⋅na⋅lB⋅na⋅l amount of power, where nana is the number of avengers and ll is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers’ base.
Input
The first line contains four integers n, k, A and B (1≤n≤30,1≤k≤105,1≤A,B≤104), where 2n2n is the length of the base, kk is the number of avengers and AA and BB are the constants explained in the question.
The second line contains kk integers a1,a2,a3,…,ak (1≤ai≤2n), where aiai represents the position of avenger in the base.
Output
Output one integer — the minimum power needed to destroy the avengers base.
Examples
input
2 2 1 2
1 3
output
6
input
3 2 1 2
1 7
output
8
#include
#include
using namespace std;
typedef unsigned long long ull;
int arr[100010];
int n,k,A,B;
ull fenzhi( ull x, ull y)
{
int num=upper_bound(arr,arr+k,y-1)-lower_bound(arr,arr+k,x);
ull ans=0;
ull mins=0x3f3f3f3f*3; //最大值
if(num==0) return A;
else
{
if(y-x>1)
{
ull mid=x+(y-x)/2;
mins=fenzhi(x,mid)+fenzhi(mid,y); //递归
}
ans=min(B*(y-x)*num,mins); //合并
}
return ans;
}
int main(int argc, char** argv)
{
cin >>n>>k>>A>>B;
for(int i=0;i>arr[i];
sort(arr,arr+k);
cout <
#include
#include
#include
using namespace std;
#define MAX 100050
#define inf 0x3f3f3f;
typedef long long ll;
struct p
{
int mins;
int id;
friend bool operator <(p a,p b)
{
return a.mins>1;
build(l,mid,i<<1);
build(mid+1,r,i<<1|1);
push_up(i);
}
p query(int l,int r,int i)
{
if(l<=tree[i].l&&tree[i].r<=r)
{
return tree[i].pi;
}
int mid=(tree[i].l+tree[i].r)>>1;
p ps;
ps.mins=inf;
ps.id=0;
if(mid>=l)
ps=min(query(l,r,i<<1),ps);
if(midr)
{
e a;
a.l=l,a.r=r,a.sum=-inf;
return a;
}
if(l==r)
{
e a;
a.sum=arr[l]*arr[l],a.l=l,a.r=r;
return a;
}
p mid=query(l,r,1);
e maxs1=max(fenzhi(l,mid.id-1),fenzhi(mid.id+1,r));
//cout <<"m1 "<>arr[i];
ans[i]=arr[i]+ans[i-1];
}
build(1,n,1);
e a=fenzhi(1,n);
cout << a.sum<< endl;
cout <