线段树单点修改的应用

思路:对初始状态进行建树,然后这题就相当于查询第一个合法的位置,并且对其值进行修改,整个题目要求维护的是区间最大值,很显然可以使用线段树。

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;
const int N = 2e6 + 5;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef array<int, 3> ar;
int mod = 1e9+7;
const int maxv = 4e6 + 5;
#define endl "\n"

int a[N],cnt[N];

int n,m,k;

struct node
{
    int l,r,val;
    #define l(x) tr[x].l
    #define r(x) tr[x].r
    #define val(x) tr[x].val
}tr[N*4];

void update(int p)
{
    val(p)=max(val(p*2),val(p*2+1));
}

void build(int p,int l,int r)
{
    if(l==r){
        tr[p]={l,r,m};
        return ;
    }
    l(p)=l,r(p)=r;
    int mid=(l+r)/2;
    build(p*2,l,mid),build(p*2+1,mid+1,r);
    update(p);
}

void query(int p,int l,int r,int x)
{
    if(l(p)==r(p)){
        cnt[l(p)]++;
        cout<<l(p)<<endl;
        val(p)-=x;
        if(cnt[l(p)]==k) val(p)=0;
        return  ;
    }
    int mid=(l(p)+r(p))/2;
    if(val(p*2)>=x) query(p*2,l,r,x);
    else if(val(p*2+1)>=x) query(p*2+1,l,r,x);
    else{
        cout<<-1<<endl;
        return ;
    }
    update(p);
}


void solve()
{
    cin>>n>>m>>k;
    for(int i=1;i<=n;i++) cin>>a[i],cnt[i]=0;
    build(1,1,n);
    for(int i=1;i<=n;i++){
        query(1,1,n,a[i]);
    }
    
} 


int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    t=1;
    cin>>t;
    while(t--){
        solve();
    }
    system("pause");
    return 0;
}
相关推荐
Echo``几秒前
2:QT联合HALCON编程—图像显示放大缩小
开发语言·c++·图像处理·qt·算法
.似水5 分钟前
2025.4.22_C_可变参数列表
java·c语言·算法
Felven25 分钟前
A. Ideal Generator
java·数据结构·算法
MoonBit月兔1 小时前
双周报Vol.70: 运算符重载语义变化、String API 改动、IDE Markdown 格式支持优化...多项更新升级!
ide·算法·哈希算法
How_doyou_do1 小时前
树状数组底层逻辑探讨 / 模版代码-P3374-P3368
数据结构·算法·树状数组
想睡hhh1 小时前
c++STL——stack、queue、priority_queue的模拟实现
开发语言·c++·stl
小鹿鹿啊1 小时前
C语言编程--14.电话号码的字母组合
c语言·开发语言·算法
cloues break.1 小时前
C++初阶----模板初阶
java·开发语言·c++
wwww.wwww2 小时前
Qt软件开发-摄像头检测使用软件V1.1
开发语言·c++·qt
小O的算法实验室2 小时前
2024年ESWA SCI1区TOP:量子计算蜣螂算法QHDBO,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进