树状数组:
用法一:区间和
Interval
时间限制:
2000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
There are n(1 <= n <= 100000) intervals [ai, bi] and m(1 <= m <= 100000) queries, -100000 <= ai <= bi <= 100000 are integers.Each query contains an integer xi(-100000 <= x <= 100000). For each query, you should answer how many intervals convers xi.
-
输入
-
The first line of input is the number of test case.
For each test case,
two integers n m on the first line,
then n lines, each line contains two integers ai, bi;
then m lines, each line contains an integer xi.
输出
- m lines, each line an integer, the number of intervals that covers xi. 样例输入
-
2 3 4 1 3 1 2 2 3 0 1 2 3 1 3 0 0 -1 0 1
样例输出
-
0 2 3 2 0 1 0
-
The first line of input is the number of test case.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int N = 100000;
const int M = N * 2 + 10;
int dp[M];
int lowbit(int n){
return n & (-n);
}
void add(int i, int plus){
while(i > 0){
dp[i] += plus;
i -= lowbit(i);
}
}
int sum(int n){
int sum = 0;
while(n <= M){
sum +=dp[n];
n += lowbit(n);
}
return sum;
}
int main(){
int ncase;
int num, query;
int from, to, now;
scanf("%d", &ncase);
while(ncase--){
int i, j;
memset(dp, 0, sizeof(dp));
cin>>num>>query;
//num = Scan(); query = Scan();
for(i = 0; i < num; ++i){
scanf("%d%d", &from, &to);
if(from == -100000){
dp[0]++;
if(to == from)
continue;
else
from++;
}
add(from - 1 + N, -1);
add(to + N, 1);
}
for(i = 0; i < query; ++i){
scanf("%d", &now);
if(now == -100000)
printf("%d\n", dp[0]);
else
printf("%d\n", sum(now + N));
}
}
return 0;
}
用法二:插线问点
士兵杀敌(四)
时间限制:
2000 ms | 内存限制:
65535 KB
难度:
5
-
描述
-
南将军麾下有百万精兵,现已知共有M个士兵,编号为1~M,每次有任务的时候,总会有一批编号连在一起人请战(编号相近的人经常在一块,相互之间比较熟悉),最终他们获得的军功,也将会平分到每个人身上,这样,有时候,计算他们中的哪一个人到底有多少军功就是一个比较困难的事情,军师小工的任务就是在南将军询问他某个人的军功的时候,快速的报出此人的军功,请你编写一个程序来帮助小工吧。
假设起始时所有人的军功都是0.
-
输入
-
只有一组测试数据。
每一行是两个整数T和M表示共有T条指令,M个士兵。(1<=T,M<=1000000)
随后的T行,每行是一个指令。
指令分为两种:
一种形如
ADD 100 500 55 表示,第100个人到第500个人请战,最终每人平均获得了55军功,每次每人获得的军功数不会超过100,不会低于-100。
第二种形如:
QUERY 300 表示南将军在询问第300个人的军功是多少。
输出
-
对于每次查询输出此人的军功,每个查询的输出占一行。
样例输入
-
4 10 ADD 1 3 10 QUERY 3 ADD 2 6 50 QUERY 3
样例输出
-
10 60
-
只有一组测试数据。
#include"stdio.h"
#define max 1000003
int c[max],m;
int lowbit(int k){
return k&(-k);
}
void add(int k,int he)//前k项都增加he
{
while(k>0){
c[k]+=he;
k-=lowbit(k);
}
}
void Q(int k)//查询
{
int query=0;
while(k<=m){
query+=c[k];
k+=lowbit(k);
}
printf("%d\n",query);
}
int main(){
int t,from,to,he;
char ch[6];
scanf("%d%d",&t,&m);
while(t--){
scanf("%s",ch);
if(ch[0]=='A'){
scanf("%d%d%d",&from,&to,&he);
add(from-1,-he);
add(to,he);
}
else if(ch[0]=='Q'){
scanf("%d",&from);
Q(from);
}
}
return 0;
}