B. Promo

time limit per test

2 seconds

memory limit per test

256 megabytes

The store sells n items, the price of the i-th item is pi. The store's management is going to hold a promotion: if a customer purchases at least x items, y cheapest of them are free.

The management has not yet decided on the exact values of x and y. Therefore, they ask you to process q queries: for the given values of x and y, determine the maximum total value of items received for free, if a customer makes one purchase.

Note that all queries are independent; they don't affect the store's stock.

Input

The first line contains two integers n and q (1≤n,q≤2⋅105) --- the number of items in the store and the number of queries, respectively.

The second line contains n integers p1,p2,...,pn (1≤pi≤106), where pi --- the price of the i-th item.

The following q lines contain two integers xi and yi each (1≤yi≤xi≤n) --- the values of the parameters x and y in the i-th query.

Output

For each query, print a single integer --- the maximum total value of items received for free for one purchase.

Example

Input

Copy

复制代码
5 3
5 3 1 5 2
3 2
1 1
5 3

Output

Copy

复制代码
8
5
6

Note

In the first query, a customer can buy three items worth 5,3,5, the two cheapest of them are 3+5=8.

In the second query, a customer can buy two items worth 5 and 5, the cheapest of them is 5.

In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is 1+2+3=6.

解题说明:此题是一道模拟题,采用贪心算法。首先根据物品价格进行排序,然后先计算出包含前面所有物品的总价。最后根据输入的查询条件直接输出结果即可。

cpp 复制代码
#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define ll long long

int main()
{
	ll n, q, x, y, i;
	cin >> n >> q;
	ll p[n + 1]; p[0] = 0;
	for (i = 0; i < n; i++)
	{
		cin >> p[i + 1];
	}
	sort(p, p + n + 1);
	for (i = 1; i <= n; i++)
	{
		p[i] += p[i - 1];
	}
	while (q--) 
	{
		cin >> x >> y;
		cout << (p[n + y - x] - p[n - x]) << endl;
	}
	return 0;
}
相关推荐
XiaoQiao6669991 小时前
C 语言常用头文件及里面核心函数
c语言·开发语言
博界IT精灵2 小时前
C语言中的数据类型及其转换
c语言·开发语言
水饺编程2 小时前
编程数学:三角函数基础01,直角三角函数
c语言·c++·windows·visual studio
LuminousCPP2 小时前
数据结构-排序(一):基础排序算法横向对比|冒泡、插入、希尔、堆与双向选择,详解二分 / Knuth 增量
c语言·数据结构·笔记·算法·排序算法
初願致夕霞2 小时前
C/C++传统程序内存分布(代码实测)
java·c语言·c++
wuyk5554 小时前
从零吃透 MQTT 通信|第 6 章 MQTT 主题、过滤器、通配符、订阅管理、拒收机制详解与代码实现
c语言·stm32·学习
phltxy13 小时前
C语言操作符详解
java·c语言·算法
RuoZoe14 小时前
从 2026 年 3 月 1 日开源,到 26.10.9:Jalium UI 半年时间到底走了多远?
c语言·c++
知无不研16 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
HRTOS18 小时前
HRTOS 4.0 驱动库:06_Storage 存储设备驱动——24C02 EEPROM与I²C驱动开发
c语言·驱动开发·嵌入式硬件·51单片机