【cogs247】售票系统【线段树】

售票系统

输入文件:railway.in 输出文件:railway.out 
时间限制:1 s 内存限制:128 MB 
【问题描述】 
某次列车途经C个城市,城市编号依次为1到C,列车上共有S个座位,铁路局规定售出的车票只能是坐票, 即车上所有的旅客都有座。售票系统是由计算机执行的,每一个售票申请包含三个参数,分别用O、D、N表示,O为起始站,D为目的地站,N为车票张数。售票 系统对该售票申请作出受理或不受理的决定,只有在从O到D的区段内列车上都有N个或N个以上的空座位时该售票申请才被受理。请你写一个程序,实现这个自动 售票系统。 
【输入格式】 
第一行包含三个用空格隔开的整数C、S和R,其中1≤C≤60000, l≤S≤60000,1≤R≤60000。C为城市个数,S为列车上的座位数,R为所有售票申请总数。接下来的R行每行为一个售票申请,用三个由空格隔开的整数O,D和N表示,O为起始站,D 为目的地站,,N为车票站数,其中1≤D≤C,1≤O≤C,所有的售票申请按申请的时间从早到晚给出。 
【输出格式】 
输出共有R行,每行输出一个“YES”或“NO”,表示当前的售票申请被受理或不被受理。 
【输入输出样例】 
Sample Input: 
4 6 4 
1 4 2 
1 3 2 
2 4 3 
1 2 3 
Sample Output: 
YES 
YES 
NO 
NO

线段树+lazy标记 
代码如下:

#include <iostream>
#include <cstdio>
using namespace std;
struct SegTreeNode {
    int lc, rc, lazy, sum;
} SegTree[600001 * 4];
int C, S, R; 
void Build(int root, int l, int r)
{
    SegTree[root].lc = l, SegTree[root].rc = r;
    if (l == r)
    {
        SegTree[root].sum = 0;
        return;
    }
    int mid = (l + r) / 2;
    Build(root * 2, l, mid);
    Build(root * 2 + 1, mid + 1, r);
    SegTree[root].sum = max(SegTree[root * 2].sum, SegTree[root * 2 + 1].sum);
} 
void pushdown(int root)
{
    int lc = root * 2, rc = root * 2 + 1;
    SegTree[lc].lazy += SegTree[root].lazy;
    SegTree[rc].lazy += SegTree[root].lazy;
    SegTree[lc].sum += SegTree[root].lazy;
    SegTree[rc].sum += SegTree[root].lazy;
    SegTree[root].lazy = 0;
}
void Modify(int root, int l, int r, int val)
{
    if (l == SegTree[root].lc && r == SegTree[root].rc)
    {
        SegTree[root].lazy += val;
        SegTree[root].sum += val;
        return;
    }
    pushdown(root);
    int mid = (SegTree[root].lc + SegTree[root].rc) / 2;
    if (r <= mid) Modify(root * 2, l, r, val);
    else if (l > mid) Modify(root * 2 + 1, l, r, val);
    else Modify(root * 2, l, mid, val), Modify(root * 2 + 1, mid + 1, r, val);
    SegTree[root].sum = max(SegTree[root * 2].sum, SegTree[root * 2 + 1].sum);
}
int Query(int root, int l, int r)
{
    if (l == SegTree[root].lc && r == SegTree[root].rc) return SegTree[root].sum;
    pushdown(root);
    int mid = (SegTree[root].lc + SegTree[root].rc) / 2;
    if (r <= mid) return Query(root * 2, l, r);
    else if (l > mid) return Query(root * 2 + 1, l, r);
    else
    {
        int p1 = Query(root * 2, l, mid), p2 = Query(root * 2 + 1, mid + 1, r);
        return max(p1, p2);
    }
}
int main()
{
    ios::sync_with_stdio(false);
    freopen("railway.in", "r", stdin);
    freopen("railway.out", "w", stdout);
    cin >> C >> S >> R;
    Build(1, 1, C);
    for (int i = 1; i <= R; i++)
    {
        int O, D, N, res=INT_MAX;
        cin >> O >> D >> N;
        D--;//这里一定要减一
        res = Query(1, O, D);
        if (res <= S - N) Modify(1, O, D, N);
        if (res <= S - N) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

  

 
原文地址:https://www.cnblogs.com/Leoleepz/p/6344998.html