#include <stdio.h>
#include <iostream>
using namespace std;
// 问题:区间和
// https://www.acwing.com/problem/content/804/
// 超时
int num[100100][2];
int n, m;
/*0 1 2
l
r
0 1 3 7
1 2 6 5*/
int putout(int);
int quicksort(int L, int R) // 根据坐标[0]排序
{
if (L >= R) return 0;
//putout(n);
int l = L-1, r = R+1;
int key = num[l+r >> 1][0];
int key1 = num[l+r >> 1][1];
int t;
while (l < r)
{
do l++; while (num[l][0] < key);
do r--; while (num[r][0] > key);
if (l < r)
{
//printf ("sort l%d r%d\n", l, r);
swap(num[l][0], num[r][0]);
swap(num[l][1], num[r][1]);
}
}
quicksort(L, r);
quicksort(r+1, R);
return 0;
}
int foundL(int x) // 找到大于等于x的最左侧数
{
int l = 0, r = n-1;
int mid;
while (l < r)
{
mid = (l+r)/2;
if (num[mid][0] >= x) r = mid;
else l = mid + 1;
}
return l;
}
int foundR(int x) // 找到小于等于x的最右侧数
{
int l = 0, r = n-1;
int mid;
while (l < r)
{
mid = (l+r+1)/2;
if (num[mid][0] <= x) l = mid;
else r = mid - 1;
}
return l;
}
int main()
{
int i, j, t;
scanf("%d%d", &n, &m);
for (i = 0; i < n; i++)
{
scanf("%d", &t);
num[i][0] = t;
scanf("%d", &t);
num[i][1] = t;
}
//putout(n);
quicksort(0, n-1);
//putout(n);
int l, r;
int sum;
for (i = 0; i < m; i++)
{
scanf("%d%d", &l, &r);
if (num[foundL(l)][0] < l || num[foundR(r)][0] > r)
{
printf ("0\n");
continue;
}
l = foundL(l); //printf ("l%d ", l);
r = foundR(r); //printf ("r%d\n", r);
sum = 0;
for (; l <= r; l++)
{
sum += num[l][1];
}
printf ("%d\n", sum);
}
return 0;
}
int putout(int n)
{
printf ("\n");
for (int i = 0; i < n; i ++)
printf ("%6d ", num[i][0]);
printf ("\n");
for (int i = 0; i < n; i ++)
printf ("%6d ", num[i][1]);
printf ("\n");
printf ("\n");
return 0;
}
08-15
1046
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-24
1937
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-30
4631
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)