描述
You are given a list of integers a0, a1, …, a2^k-1.
You need to support two types of queries:
1. Output Minx,y∈[l,r] {ax∙ay}.
2. Let ax=y.
输入
The first line is an integer T, indicating the number of test cases. (1≤T≤10).
For each test case:
The first line contains an integer k (0 ≤ k ≤ 17).
The following line contains 2k integers, a0, a1, …, a2^k-1 (-2k ≤ ai < 2k).
The next line contains a integer (1 ≤ Q < 2k), indicating the number of queries. Then next Q lines, each line is one of:
1. 1 l r: Output Minx,y∈[l,r]{ax∙ay}. (0 ≤ l ≤ r < 2k)
2. 2 x y: Let ax=y. (0 ≤ x < 2k, -2k ≤ y < 2k)
输出
For each query 1, output a line contains an integer, indicating the answer.
1 3 1 1 2 2 1 1 2 2 5 1 0 7 1 1 2 2 1 2 2 2 2 1 1 2
1 1 4
题意很简单,就是给 n个数,让进行两种操作,1、查询[ l,r ]间 ai*aj 的最小值;2、更改第 i 个元素为x。
很显然的线段树,包含两个基本操作,区间查询和单点更新。
要注意的地方,由于数组元素可能会有负数,所以要求的最小乘积可能是负的。在区间维护两个值,1 是最大值Max,2 是最小值Min,这样查询结果有三种可能:1、一正一负,Max*Min;2、两个正数,Min*Min;3、两个负数 Max*Max。
代码如下:
#include<stdio.h>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
#define lson k*2, left, mid
#define rson k*2+1, mid+1, right
const int MAXN =131100;
int MAX[MAXN*4],MIN[MAXN*4];
void pushUpMax(int k)
{
MAX[k]=max(MAX[k*2], MAX[k*2+1]);
}
void pushUpMin(int k)
{
MIN[k]=min(MIN[k*2], MIN[k*2+1]);
}
void build(int k, int left, int right)
{
if(left==right)
{
scanf("%d", &MAX[k]);
MIN[k]=MAX[k];
return ;
}
int mid=(left+right)/2;
build(lson);
build(rson);
pushUpMax(k);
pushUpMin(k);
}
void update(int k, int left, int right, int pos, int v)
{
if(left==right)
{
MIN[k]=MAX[k]=v;
return ;
}
int mid=(left+right)/2;
if (pos<=mid)
update(lson, pos, v);
else
update(rson, pos, v);
pushUpMax(k);
pushUpMin(k);
}
int queryMin(int k, int left, int right, int L, int R)
{
if(left>=L && right<=R)
{
return MIN[k];
}
int mid=(left+right)/2;
int ans=MAXN;
if (L<=mid) ans=min(ans, queryMin(lson, L, R));
if (R>mid) ans=min(ans, queryMin(rson, L, R));
return ans;
}
int queryMax(int k, int left, int right, int L, int R)
{
if(left>=L && right<=R)
{
return MAX[k];
}
int mid=(left+right)/2;
int ans=-MAXN;
if (L<=mid) ans=max(ans, queryMax(lson, L, R));
if (R>mid) ans=max(ans, queryMax(rson, L, R));
return ans;
}
int main()
{
int T, n, m;
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
n=pow(2, n);
build(1, 1, n);
scanf("%d", &m);
while(m--)
{
int a, b, ch;
scanf("%d%d%d", &ch, &a, &b);
a++;
if(ch==1)
{
b++;
ll t1=(ll)queryMin(1, 1, n, a, b);
ll t2=(ll)queryMax(1, 1, n, a, b);
ll ans;
if(t1<=0 && t2>=0)
{
ans=t1*t2;
printf("%lld\n", ans);
}
else
{
ans=min(t2*t2, t1*t1);
printf("%lld\n", ans);
}
}
else update(1, 1, n, a, b);
}
}
return 0;
}