线段树单点修改的应用

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

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;
}
相关推荐
闪电麦坤953 分钟前
数据结构:N个节点的二叉树有多少种(Number of Binary Trees Using N Nodes)
数据结构·二叉树·
快去睡觉~1 小时前
力扣400:第N位数字
数据结构·算法·leetcode
徐归阳1 小时前
第二十四天:虚函数与纯虚函数
c++
青草地溪水旁1 小时前
UML函数原型中constraint的含义,有啥用?
c++·uml
qqxhb2 小时前
零基础数据结构与算法——第七章:算法实践与工程应用-搜索引擎
算法·搜索引擎·tf-idf·倒排索引·pagerank·算法库
gzzeason3 小时前
LeetCode Hot100:递归穿透值传递问题
算法·leetcode·职场和发展
汤永红3 小时前
week1-[循环嵌套]画正方形
数据结构·c++·算法
pusue_the_sun3 小时前
数据结构——顺序表&&单链表oj详解
c语言·数据结构·算法·链表·顺序表
重启的码农3 小时前
ggml 介绍(4) 计算图 (ggml_cgraph)
c++·人工智能
重启的码农3 小时前
ggml 介绍(5) GGUF 上下文 (gguf_context)
c++·人工智能·神经网络