Codeforces Round #215 (Div. 1) C. Sereja and the Arrangement of Numbers(欧拉图)

来源:互联网 发布:手表品牌排行榜 知乎 编辑:程序博客网 时间:2024/06/14 07:12

Let's call an array consisting of n integer numbers a1a2...anbeautiful if it has the following property:

  • consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a;
  • for each pair x, y must exist some position j (1 ≤ j < n), such that at least one of the two conditions are met, either aj = x, aj + 1 = y, or aj = y, aj + 1 = x.

Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi, wi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.

Help Sereja, find the maximum amount of money he can pay to Dima.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 105). Next m lines contain pairs of integers. The i-th line contains numbers qi, wi (1 ≤ qi, wi ≤ 105).

It is guaranteed that all qi are distinct.

Output

In a single line print maximum amount of money (in rubles) Sereja can pay.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cincout streams or the %I64dspecifier.

Examples
input
5 21 22 3
output
5
input
100 31 22 13 1
output
4
input
1 21 12 100
output
100
Note

In the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test.

In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2].

分析:将每个数字看成点,两个数字相邻就连一条无向边,这样每个点的度数为 n-1,如果n为奇数那么原图就是欧拉图,这样至少要连n*(n-1)/2条边;如果n为偶数那么每个点的度数都为奇数,我们需要再至少添加 n/2 - 1条边,才能保证图中存在一条欧拉通路,这样至少要连n*(n-1)/2 + n/2 - 1条边。

然后我们就可以二分最多加几个数字进来了,因为数字是什么无关紧要,所以我们将数字按权值排好序之后取大的就可以了。

#include<iostream>#include<string>#include<algorithm>#include<cstdlib>#include<cstdio>#include<set>#include<map>#include<vector>#include<cstring>#include<stack>#include<queue>#define INF 4557430888798830400ll#define eps 1e-9#define MAXN 0x3f#define N 100005using namespace std;long long ans;int n,m,q[N],w[N];long long f(int x){if(x & 1) return 1ll*x*(x-1)/2 + 1;else return 1ll*x*(x-1)/2 + x/2;}int main(){scanf("%d%d",&n,&m);for(int i = 1;i <= m;i++) scanf("%d%d",&q[i],&w[i]);int s = 1,t = m;while(s != t){int mid = ((s+t)>>1) + 1;if(f(mid) <= n) s = mid;else t = mid - 1;}sort(w+1,w+1+m);for(int i = 1;i <= s;i++) ans += w[m-i+1];cout<<ans<<endl; }


0 0
原创粉丝点击