Fast Arrangement
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 4023 Accepted Submission(s): 1151
Problem Description
Chinese always have the railway tickets problem because of its’ huge amount of passangers and stations. Now goverment need you to develop a new tickets query system.
One train can just take k passangers. And each passanger can just buy one ticket from station a to station b. Each train cannot take more passangers any time. The one who buy the ticket earlier which can be sold will always get the ticket.
Input
The input contains servel test cases. The first line is the case number. In each test case:
The first line contains just one number k( 1 ≤ k ≤ 1000 ) and Q( 1 ≤ Q ≤ 100000 )
The following lines, each line contains two integers a and b, ( 1 ≤ a < b ≤ 1000000 ), indicate a query.
Huge Input, scanf recommanded.
Output
For each test case, output three lines:
Output the case number in the first line.
If the ith query can be satisfied, output i. i starting from 1. output an blank-space after each number.
Output a blank line after each test case.
Sample Input
1
3 6
1 6
1 6
3 4
1 5
1 2
2 4
Sample Output
Case 1:
1 2 3 5
线段树区间查找、区间加减的模板题,值得说明的就是用lazy存储要加减的值而不用一次更改到底,节约时间复杂度。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define MAXL 100005
struct node
{
int l,r;
long long total;
long long lazy;
}tree[MAXL<<2];
long long ori[MAXL];
void build(int k,int l,int r)//初始化建树
{
tree[k].l=l;tree[k].r=r;
if(l==r)
{
tree[k].total=ori[l];
tree[k].lazy=0;
return;
}
int mid=(l+r)/2;
build(k<<1,l,mid);
build(k<<1|1,mid+1,r);
tree[k].total=tree[k<<1].total+tree[k<<1|1].total;
tree[k].lazy=0;
}
void command(int k)//处理lazy标记
{
if(tree[k].l!=tree[k].r)
{
tree[k<<1].total+=(tree[k<<1].r-tree[k<<1].l+1)*tree[k].lazy;
tree[k<<1|1].total+=(tree[k<<1|1].r-tree[k<<1|1].l+1)*tree[k].lazy;
tree[k<<1].lazy+=tree[k].lazy;
tree[k<<1|1].lazy+=tree[k].lazy;
}
tree[k].lazy=0;
}
long long ques(int k,int l,int r)//区间询问
{
if (tree[k].lazy)
command(k);
if(tree[k].l==l&&tree[k].r==r)
return tree[k].total;
int mid=(tree[k].l+tree[k].r)/2;
if(r<=mid) return ques(k<<1,l,r);
else if(l>mid) return ques(k<<1|1,l,r);
else return ques(k<<1,l,mid)+ques(k<<1|1,mid+1,r);
}
void add(int k,int l,int r,long long val)//区间加减
{
if(tree[k].lazy)
command(k);
if(tree[k].l==l&&tree[k].r==r)
{
tree[k].lazy=val;
tree[k].total+=val*(r-l+1);
return;
}
int mid=(tree[k].l+tree[k].r)>>1;
if(mid<l) add(k<<1|1,l,r,val);
else if(mid>=r) add(k<<1,l,r,val);
else {add(k<<1,l,mid,val);add(k<<1|1,mid+1,r,val);}
tree[k].total=tree[k<<1].total+tree[k<<1|1].total;
return ;
}
int main(void)
{
int n,q;
while(~scanf("%d%d",&n,&q))
{
for(int i=1;i<=n;i++)
{
scanf("%lld",&ori[i]);
}
build(1,1,n);
char order[2];
int a,b;
for(int i=0;i<q;i++)
{
scanf("%s%d%d",order,&a,&b);
if(order[0]=='Q')
printf("%lld\n",ques(1,a,b));
else {
int c;
scanf("%d",&c);
add(1,a,b,c);
}
}
}
return 0;
}