传送门:点击打开链接
The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). You need to find for each query the sum of elements of the array with indexes from li to ri, inclusive.
The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
The first line contains two space-separated integers n (1 ≤ n ≤ 2·105) and q (1 ≤ q ≤ 2·105) — the number of elements in the array and the number of queries, correspondingly.
The next line contains n space-separated integers ai (1 ≤ ai ≤ 2·105) — the array elements.
Each of the following q lines contains two space-separated integers li and ri (1 ≤ li ≤ ri ≤ n) — the i-th query.
In a single line print a single integer — the maximum sum of query replies after the array elements are reordered.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
3 3 5 3 2 1 2 2 3 1 3
25
5 3 5 2 4 1 3 1 5 2 3 2 3
33
题意:给一个数列长度为n,和m次询问,对于每一次询问,记Qi=sum(a[Li]~a[Ri])。让你重新调整数列a[i]的顺序,使Sigm(Qi)最大。输出这个Sigm
思路:对于每一个位置,求出在Sigm(Qi)中,这个位置的数被加了多少次。对于累加次数最多的位置,我们给他填最大的数,依此贪心,得到的Sigm就是最大的。
对于每一个询问,我们可以看作是在区间[Li,Ri]上的所有位置的累加次数都要+1。这就是个线段树的区间累加,单点询问的操作。得到每个位置被累计的次数后,我们就可以按照上面的方法就行贪心求解。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
#define maxn 200005
using namespace std;
struct node
{
int c, l, r;
}tree[maxn << 2];
inline void pushdown(int id)
{
if (tree[id].c)
{
tree[id << 1].c += tree[id].c;
tree[id << 1 | 1].c += tree[id].c;
tree[id].c = 0;
}
}
void build(int id, int l, int r)
{
tree[id].l = l;
tree[id].r = r;
tree[id].c = 0;
if (l != r)
{
int mid = (l + r) >> 1;
build(id << 1, l, mid);
build(id << 1 | 1, mid + 1, r);
}
}
void op(int id, int l, int r)
{
if (l <= tree[id].l&&tree[id].r <= r) tree[id].c++;
else
{
pushdown(id);
int mid = (tree[id].l + tree[id].r) >> 1;
if (l <= mid) op(id << 1, l, r);
if (mid<r) op(id << 1 | 1, l, r);
}
}
int a[maxn], b[maxn];
void out(int id)
{
if (tree[id].l == tree[id].r) b[tree[id].l] = tree[id].c;
else
{
pushdown(id);
out(id << 1);
out(id << 1 | 1);
}
}
int main()
{
int n, q;
scanf("%d %d", &n, &q);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
build(1, 1, n);
while (q--)
{
int l, r;
scanf("%d %d", &l, &r);
op(1, l, r);
}
out(1);
sort(b + 1, b + 1 + n);
sort(a + 1, a + 1 + n);
LL ans = 0;
for (int i = 1; i <= n; i++) ans += (LL)a[i] * b[i];
printf("%I64d\n", ans);
return 0;
}