线段树单点修改的应用

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

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;
}
相关推荐
刘琦沛在进步25 分钟前
【C / C++】引用和函数重载的介绍
c语言·开发语言·c++
我在人间贩卖青春1 小时前
C++之this指针
c++·this
爱敲代码的TOM1 小时前
数据结构总结
数据结构
云姜.1 小时前
java多态
java·开发语言·c++
CoderCodingNo1 小时前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
陳10301 小时前
C++:红黑树
开发语言·c++
大闲在人1 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
一切尽在,你来1 小时前
C++ 零基础教程 - 第 6 讲 常用运算符教程
开发语言·c++
小熳芋2 小时前
443. 压缩字符串-python-双指针
算法
Charlie_lll2 小时前
力扣解题-移动零
后端·算法·leetcode