1128 - 咸鱼拷问(“玲珑杯”线上赛 Round #15 河南专场)
题目链接:http://ifrog.cc/acm/problem/1128
思路有两种:
- 线段树查区间最小值和最大值
- RMQ查区间最小值和最大值
线段树代码:
#include<bits/stdc++.h>
using namespace std;
const long long INF = 0x3f3f3f3f;
long long n;
long long a[100007], b[100007];
struct node
{
long long l, r, x, y;
};
node tree[100007 << 2];
void build(long long l, long long r, long long k)
{
tree[k].l = l, tree[k].r = r;
if(l == r)
{
tree[k].x = tree[k].y = a[l];
return;
}
long long mid = (l + r) >> 1;
build(l, mid, k << 1);
build(mid+1, r, k << 1|1);
tree[k].x = max(tree[k<<1].x, tree[k<<1|1].x);
tree[k].y = min(tree[k<<1].y, tree[k<<1|1].y);
}
long long query_x(long long l, long long r, long long k)
{
if(tree[k].l >= l && tree[k].r <= r)
{
return tree[k].x;
}
long long res = -1e10-7;
if(tree[k<<1].r >= l)
res = max(res, query_x(l, r, k<<1));
if(tree[k<<1|1].l <= r)
res = max(res, query_x(l, r, k<<1|1));
return res;
}
long long query_y(long long l, long long r, long long k)
{
if(tree[k].l >= l && tree[k].r <= r)
{
return tree[k].y;
}
long long res = 1e10+7;
if(tree[k<<1].r >= l)
res = min(res, query_y(l, r, k<<1));
if(tree[k<<1|1].l <= r)
res = min(res, query_y(l, r, k<<1|1));
return res;
}
int main()
{
while(scanf("%d", &n) != EOF)
{
for(long long i=1; i<=n; ++ i)
scanf("%lld", &a[i]);
for(long long i=1; i<=n; ++ i)
scanf("%lld", &b[i]);
build(1, n, 1);
for(long long i=1; i<=n; ++ i)
{
long long x = query_x(i-b[i]+1, i, 1);
long long y = query_y(i-b[i]+1, i, 1);
printf("%lld\n", x * y);
}
}
return 0;
}
RMQ代码
#include<bits/stdc++.h>
using namespace std;
int a[100007], b[100007];
int mx[100007][20], mn[100007][20];
void RMQ(int num)
{
memset(mx, 0, sizeof(mx));
memset(mn, 0, sizeof(mn));
for(int i=1; i<=num; ++ i)
mx[i][0] = mn[i][0] = a[i];
for(int j=1; j<=20; ++ j)
{
for(int i=1; i<=num; ++ i)
{
if(i + (1 << j) - 1 <= num)
{
mx[i][j] = max(mx[i][j-1], mx[i+(1 << (j-1))][j-1]);
mn[i][j] = min(mn[i][j-1], mn[i+(1 << (j-1))][j-1]);
}
}
}
}
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
for(int i=1; i<=n; ++ i)
scanf("%d", &a[i]);
for(int i=1; i<=n; ++ i)
scanf("%d", &b[i]);
RMQ(n);
for(int i=1; i<=n; ++ i)
{
int t = (log10(b[i]) / log10(2));
long long x = max(mx[i-b[i]+1][t], mx[i-(1<<t)+1][t]);
long long y = min(mn[i-b[i]+1][t], mn[i-(1<<t)+1][t]);
printf("%lld\n", x*y);
}
}
return 0;
}