Go
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
func getKeys(m map[int]int) []int {
keys := make([]int, 1, len(m)+1)
for k := range m {
keys = append(keys, k)
}
return keys
}
func lowerBound(values []int, v int) int {
low, high := 1, len(values)-1
if v > values[high] {
return high+1
}
for low < high {
mid := (low + high) / 2
if values[mid] < v {
low = mid + 1
} else {
high = mid
}
}
return low
}
func upperBound(values []int, v int) int {
low, high := 1, len(values)-1
if v < values[low] {
return low-1
}
for low < high {
mid := (low + high + 1) / 2
if values[mid] > v {
high = mid - 1
} else {
low = mid
}
}
return high
}
func main() {
in := bufio.NewReader(os.Stdin)
var n, m int
fmt.Fscan(in, &n, &m)
cup := make(map[int]int)
for i := 0; i < n; i++ {
var x, c int
fmt.Fscan(in, &x, &c)
cup[x] += c
}
keys := getKeys(cup)
sort.Ints(keys[1:])
sums := make([]int, len(keys))
for i := 1; i < len(sums); i++ {
sums[i] = sums[i-1] + cup[keys[i]]
}
for i := 0; i < m; i++ {
var l, r int
fmt.Fscan(in, &l, &r)
l, r = lowerBound(keys, l), upperBound(keys, r)
fmt.Println(sums[r] - sums[l-1])
}
}
C++
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
int lowerBound(const vector<int>& values, int v) {
int low = 1, high = values.size() - 1;
if (v > values[high]) {
return high + 1;
}
while (low < high) {
int mid = (low + high) >> 1;
if (values[mid] < v) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
int upperBound(const vector<int>& values, int v) {
int low = 1, high = values.size() - 1;
if (v < values[low]) {
return low + 1;
}
while (low < high) {
int mid = (low + high + 1) >> 1;
if (values[mid] > v) {
high = mid - 1;
} else {
low = mid;
}
}
return high;
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
unordered_map<int, int> cup;
for (int i = 0; i < n; ++i) {
int x, c;
scanf("%d %d", &x, &c);
cup[x] += c;
}
vector<int> keys(1, 0);
for (const auto& p : cup) {
keys.push_back(p.first);
}
sort(keys.begin()+1, keys.end());
vector<int> sums(keys.size(), 0);
for (int i = 1; i < sums.size(); ++i) {
sums[i] = sums[i-1] + cup[keys[i]];
}
for (int i = 0; i < m; ++i) {
int l, r;
scanf("%d %d", &l, &r);
l = lowerBound(keys, l);
r = upperBound(keys, r);
printf("%d\n", sums[r] - sums[l-1]);
}
return 0;
}