ljx_gkx @ 2023-04-07 14:50:34
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e6 + 10;
int a[N];
int n, m;
struct Node{
int l, r;
int val;
}tr[N*4-1];
void pushup(int u) //利用子节点的信息向上更新父节点的信息,本题中需要更新的是父节点的区间的最小值!
{
tr[u].val = min(tr[u<<1].val, tr[u<<1|1].val);
return ;
}
void build(int u, int l, int r)
{
tr[u] = {l, r};
if (l == r){
tr[u].val = a[r];
return ;
}
//给当前区间分配左右端点!
int mid = (l+r) >> 1;
build(u<<1, l, mid), build(u<<1|1, mid+1, r);
pushup(u);
}
int query (int u, int l, int r)
{
if (tr[u].l >= l && tr[u].r <= r)
{
return tr[u].val;
}
int mid = (tr[u].l + tr[u].r) >> 1;
int res = 0x3f3f3f3f;
if (l <= mid) res = min(res, query(u<<1, l, r));
if (r > mid) res = min(res, query(u<<1|1, l, r));
return res;
}
int main()
{
cin >> n >> m;
for (int i=1; i <= n; i ++)
cin >> a[i];
build(1, 1, n);
for (int i=1; i <= n; i ++)
{
int l = i-m, r = i-1;
if (l <= 0) cout << 0 << endl;
else
cout << query(1, l, r) << endl;
}
return 0;
}
by jacklee10086 @ 2023-04-07 14:57:43
题目要求为若前面的数不足m项则从第1个数开始,若前面没有数则输出0。你的代码似乎是若前面的数不足m项则输出0了
by jacklee10086 @ 2023-04-07 15:03:30
给你简单改了一下
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e6 + 10;
int a[N];
int n, m;
struct Node{
int l, r;
int val;
}tr[N*4-1];
void pushup(int u) //利用子节点的信息向上更新父节点的信息,本题中需要更新的是父节点的区间的最小值!
{
tr[u].val = min(tr[u<<1].val, tr[u<<1|1].val);
return ;
}
void build(int u, int l, int r)
{
tr[u] = {l, r};
if (l == r){
tr[u].val = a[r];
return ;
}
//给当前区间分配左右端点!
int mid = (l+r) >> 1;
build(u<<1, l, mid), build(u<<1|1, mid+1, r);
pushup(u);
}
int query (int u, int l, int r)
{
if (tr[u].l >= l && tr[u].r <= r)
{
return tr[u].val;
}
int mid = (tr[u].l + tr[u].r) >> 1;
int res = 0x3f3f3f3f;
if (l <= mid) res = min(res, query(u<<1, l, r));
if (r > mid) res = min(res, query(u<<1|1, l, r));
return res;
}
int main()
{
cin >> n >> m;
for (int i=1; i <= n; i ++)
cin >> a[i];
build(1, 1, n);
for (int i=1; i <= n; i ++)
{
int l = max(i-m,1), r = i-1;
if (r <= 0) cout << 0 << endl;
else
cout << query(1, l, r) << endl;
}
return 0;
}
by jacklee10086 @ 2023-04-07 15:12:35
btw,这道题的正解是滑动窗口,虽然线段树可做但是要卡个常数。