线段树单点修改的应用

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

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;
}
相关推荐
wefg130 分钟前
【C++】类与对象
开发语言·c++
Dr.92744 分钟前
1-10 目录树
java·数据结构·算法
双叶8361 小时前
(C语言)超市管理系统 (正式版)(指针)(数据结构)(清屏操作)(文件读写)(网页版预告)(html)(js)(json)
c语言·javascript·数据结构·html·json
子豪-中国机器人1 小时前
C++ 蓝桥 STEMA 省选拔赛模拟测试题(第一套)
开发语言·c++·算法
callJJ1 小时前
Bellman - Ford 算法与 SPFA 算法求解最短路径问题 ——从零开始的图论讲解(4)
数据结构·算法·蓝桥杯·图论·单源最短路径·bellman- ford算法
圈圈编码1 小时前
LeetCode Hot100刷题——轮转数组
java·算法·leetcode·职场和发展
虾球xz1 小时前
游戏引擎学习第286天:开始解耦实体行为
c++·人工智能·学习·游戏引擎
zh_xuan3 小时前
c++ 类的语法3
开发语言·c++
一律清风4 小时前
【Opencv】canny边缘检测提取中心坐标
c++·opencv
金融小师妹5 小时前
应用BERT-GCN跨模态情绪分析:贸易缓和与金价波动的AI归因
大数据·人工智能·算法