Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful 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 cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
Output
5
Input
100 3
1 2
2 1
3 1
Output
4
Input
1 2
1 1
2 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].
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to interpret the problem carefully. We have n (length of array) up to 2e6, m up to 1e5, each coupon gives a number qi (distinct) and a cost wi (presumably per occurrence? Wait: "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." So for each element in array a that equals qi, Sereja pays wi. Since multiple occurrences, total cost = sum over all array elements of cost of that number? Actually: "takes wi rubles from Sereja for each qi, which occurs in the array a." This could be interpreted as: if the number qi appears at least once, Sereja pays wi (once) per distinct qi present? Or per occurrence? Let's examine sample 1: n=5, m=2: (1,2) and (2,3). Output 5. If per occurrence: maximum payment? They say optimal array [1,2,1,2,2] gives total cost: occurrences: two 1's -> 22=4? Actually w1=2 per 1, w2=3 per 2. Count: 1 appears twice: 22=4; 2 appears three times: 3*3=9; total =13 >5. So not per occurrence. If per distinct: then if both numbers appear, pay 2+3=5. That matches output 5. Also array [2,2,2,2,2] would have only number 2, pay 3, which is less. So we want to maximize sum of wi over distinct numbers used in the array.
But wait: sample 2: n=100, m=3: (1,2),(2,1),(3,1). Output 4. If per distinct: max possible sum = 2+1+1=4, but is it feasible to use all three numbers in a beautiful array of length 100? Yes likely. So output 4 matches. Sample 3: n=1, m=2: (1,1),(2,100). Output 100. For n=1, we can only have one element. The array of length 1: can it be beautiful? Let's verify the property: "consider all pairs of numbers x,y (x≠y) such that number x occurs in the array and number y occurs in the array; for each pair (x,y) must exist some position j (1≤j<n) such that either aj=x and aj+1=y or aj=y and aj+1=x." For n=1, there are no positions j (since j from 1 to n-1, n-1=0). So condition involves pairs of distinct numbers that occur. If only one number occurs, then there are no pairs (x,y) with x≠y). So the condition vacuously holds? Typically, universal quantification over empty set is true. So array with one element is beautiful regardless of its value? But must consider condition: "consider all pairs of numbers x,y (x≠y) such that number x occurs in the array and number y occurs in the array". If only one distinct number, set of such pairs is empty, condition holds. So beautiful. So we can choose number 2 only, giving cost 100. So again per distinct number.
Thus we need to maximize sum of wi over distinct numbers we include in the array, subject to being able to construct a beautiful array of length n that uses exactly that set of numbers (maybe using each number at least once) and no other numbers? Actually we can also use numbers not in coupons? The coupons are the only numbers that Dima can use? Wait: The problem: "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." That implies Dima can only use numbers from the coupons? Because the coupons allow you to use numbers qi as many times as you want. Sereja has no coupons, so if Dima wants to use a number not in any coupon, is he allowed? The phrase "allows you to use as many numbers qi as you want when constructing the array a" suggests that to use a number, you need a coupon. Since Dima has the coupons, he can use those numbers for free (well, he then charges Sereja). So the array a can only contain numbers from the set Q = {q_i}? There is no other way to include a number not in a coupon. So a subset S of Q is chosen, and Dima must construct a beautiful array of length n using numbers from S (each used at least once, because if a number from S is included in the set of occurring numbers, it must appear at least once; but could we include a coupon number but not actually use it? The payment is for each qi which occurs in the array. So if we want to charge for qi, we must include it at least once. If we don't include it, no payment. So we choose some subset S of Q to include, maximizing sum_{i in S} w_i, such that there exists a beautiful array of length n with exactly the set of distinct numbers = S (or a superset? Actually we could include extra numbers not in coupons? Not allowed. So only numbers from coupons can appear. But we could also include some coupon numbers but not all? Yes. So we need to determine for which subsets S can we construct a beautiful array of length n using numbers from S (each at least once). The array may use numbers not in S? It cannot, because only numbers from coupons can appear. If we include a coupon number, it's in S. If we don't include it, we can't use it. So the set of distinct numbers in array is exactly S (assuming we use each number in S at least once, and no others). So we need to characterize the possible S that admit a beautiful array of length n.
Now, the condition: For any two distinct numbers x,y in S, there exists an adjacent pair (in some order) somewhere in the array: either x followed by y, or y followed by x.
Thus the requirement is that the set S is such that we can arrange numbers (with possible repetitions) into a sequence of length n, where each number from S appears at least once, and for each unordered pair {x,y}, at least one of the two ordered adjacencies appears somewhere.
This is reminiscent of constructing a graph where vertices are numbers in S, and we need a sequence (a walk with repetitions) that covers all vertices and such that for every pair of vertices, the edge between them is traversed at least once (in either direction). In a sequence, an adjacency (a_j, a_{j+1}) corresponds to an edge in the complete graph on S (directed, but undirected condition requires either direction). So the condition is: for every unordered pair {u,v}, the undirected edge must appear at some point as consecutive elements.
Given that we can repeat vertices arbitrarily, we need to produce a sequence of length n that covers all vertices and covers all edges. Is it possible for any set S? Let's think.
We have a multigraph (walk) on vertex set S. We need to ensure that each undirected edge is traversed at least once. This is similar to the concept of "line covering" or "covering all edges by a walk". For a walk (allowing repeated vertices and edges) to cover all edges of a complete graph on |S| = k vertices, what is the minimum length needed? And can we extend to any n >= that minimum? Also note that we can include extra steps (repeating edges or vertices) arbitrarily, as long as all required edges appear at least once. So the feasibility condition for a given S is: there exists a walk of length n (i.e., n vertices, n-1 edges) that starts and ends at some vertices, such that all edges of the complete graph K_k are present among the traversed edges (at least once). And we must also ensure that each vertex appears at least once, which is implied if we cover all edges because edges incident to a vertex will cause that vertex to appear.
But the walk's length is n, which can be huge (up to 2e6). So we need to check if n is at least the minimal number of vertices (or edges) needed to cover all edges of K_k. Since we can repeat edges, the question reduces to: given k, what is the minimal length L (number of vertices) of a sequence (with n vertices) such that the set of consecutive pairs covers all unordered pairs? Equivalent to: what is the minimum number of edges (n-1) required in a walk that covers all edges of K_k? This is known as the "covering walk" or "route" covering all edges. For a complete graph, the minimal length of a closed walk that traverses each edge at least once? Or open walk? In our case, we don't require closed; we just need a sequence of vertices of length n, so edges used are between consecutive vertices. So we need to find minimal number of vertices (or edges) for which such a sequence exists.
This is akin to finding the shortest walk that covers all edges of a graph (the "route inspection" for edges, not vertices). That's the Chinese Postman Problem (CPP) for undirected graphs: find a shortest closed walk that traverses each edge at least once. For any graph, the solution involves pairing odd-degree vertices. For a complete graph K_k, we can compute the length of the shortest closed walk covering all edges (Eulerian trail after adding duplicate edges to make all vertices even). But we need an open walk of length n (i.e., number of vertices = n). However, we can always transform a closed walk into an open walk by removing one vertex from the end? Actually a closed walk starts and ends at same vertex; an open walk can start and end at different vertices. The minimum number of edges needed to cover all edges at least once in an open walk is the Chinese postman problem for open walk? Typically the CPP finds minimal length closed walk; open walk might be shorter? But you could start at one vertex and end at another, you may avoid returning to start, potentially saving some edges. However, covering all edges often requires traversing some edges multiple times because the graph may not have an Eulerian trail (which requires exactly 0 or 2 odd-degree vertices). An Eulerian trail exists if at most two vertices have odd degree. For K_k, all vertices have degree k-1. So parity of k-1: If k is odd, then k-1 is even, so all degrees even, so K_k is Eulerian, meaning there exists a closed Eulerian circuit that traverses each edge exactly once. That's length = number of edges + 1 vertices? Actually Eulerian circuit is a closed walk that uses each edge exactly once, so number of edges traversed = number of edges in graph = k(k-1)/2. Number of vertices in sequence = edges + 1 (since a walk with E edges has E+1 vertices, starting and ending at same vertex if closed). So minimal sequence length (number of vertices) for a closed walk covering all edges exactly once is L_closed = k(k-1)/2 + 1, if k odd? Wait, for Eulerian circuit, we traverse each edge exactly once, so total edges traversed = |E| = k(k-1)/2. The walk is a sequence of vertices v0, v1, ..., v_{|E|} with v0 = v_{|E|}. So number of vertices in the sequence = |E| + 1 (including the repeated endpoint counted twice? Actually v0 is start, v_{|E|} is end, which equals v0, so the sequence is of length |E|+1 terms, but we might count the endpoint only once in the array representation? In array a of length n, we list a1,...,an. In a walk, a_i are vertices. If we have a closed Eulerian circuit that returns to start, we can list all vertices visited, including the final vertex which is same as start. For array length, if we have a closed circuit of E edges, we have E+1 vertices; if we end at the same vertex, the last vertex equals first, but it's still a distinct position in the array. So length = E+1. So minimal n for an array that is a closed Eulerian circuit covering all edges exactly once is n = E+1.
But we can also have an open Eulerian trail if exactly two vertices have odd degree. For K_k, if k is even, then k-1 is odd, so all vertices have odd degree. So number of odd-degree vertices = k, which is even? Actually k could be even; then each vertex degree = odd (since k-1 odd). So there are k odd vertices. For an undirected graph to have an Eulerian trail (open), it must have exactly 0 or 2 odd vertices. So K_k for even k does not have an Eulerian trail. We would need to duplicate some edges to reduce odd vertices to 0 or 2. That is the Chinese postman: we need to add duplicate edges to make all vertices even, except possibly two for an open walk. But we are free to have an open walk? The array can start and end anywhere, not necessarily same. So we want the minimal number of edges in a walk that covers every edge at least once. For a graph, the minimal length of an open walk covering all edges is the Chinese postman problem for open route? Usually CPP finds minimal closed walk covering all edges. For an open walk, we can consider starting and ending at two specified vertices; the minimal covering walk that starts at s and ends at t is essentially the closed CPP on the graph with added edges to make s and t odd? Actually there is a known result: the shortest open walk that traverses all edges at least once can be found by considering the graph with added edges to make all vertices even except s and t odd, then find Eulerian trail. So the minimal extra edges needed is the minimum weight matching among odd vertices, but we also have the choice of s and t. So to minimize total traversed edges, we can choose s and t to be the two vertices that are paired in the matching. In effect, the minimal number of edges to traverse all edges at least once is: |E| + (minimum weight of a matching on the odd-degree vertices) if we require a closed walk? Actually for closed walk, we need to make all vertices even, so we add a minimum weight matching on the odd vertices. For open walk, we can leave two vertices odd, so we add a minimum weight matching on all odd vertices except we choose two to remain odd; equivalently, we need to add a minimum weight set of edges to make all vertices even except two, which is like matching on all odd vertices but leaving two unmatched; that matching weight is minimum over choices of which two to leave unmatched of min matching on the rest? More precisely: For a graph with odd vertex set O (|O| even), the Chinese postman closed walk adds a minimum perfect matching on O, duplicating those edges, so total edges traversed = |E| + weight(M). For an open walk starting at s and ending at t, we want an Eulerian trail from s to t; this is possible iff all vertices have even degree except s and t which are odd. So we need to add edges to make degrees even except s,t odd. That can be achieved by adding a minimum weight matching on O \ {s,t}? Actually starting from original graph (all vertices degrees maybe odd/even). To get an Eulerian trail from s to t, we need s and t odd (if they were even, we must make them odd by adding a self-loop? Not allowed). Equivalent: we need to add edges (duplicates) to change parity appropriately. The parity condition: after additions, degrees mod2: even for all vertices except s and t (which are odd). So we need to find a multiset of edges (duplicates) such that the parity changes: For each vertex v, the number of added edges incident to v modulo 2 should be equal to desired parity change (0 if we want even, 1 if we want odd). This is a T-join problem: find minimum weight set of edges (in the metric closure) to connect a set T of vertices with odd cardinality. For closed CPP, T = O (set of odd vertices), we need a set of edges such that each vertex in O gets odd degree from added edges, others even => that's a T-join. For open CPP with specified s,t, T = O Δ {s,t}? Actually if original O is set of odd vertices. Desired odd vertices = {s,t}. So we need to change parity for vertices: For v in O but not in {s,t}, we need to flip parity (odd->even) => need 1 added incident edge (mod2) to that vertex. For v in {s,t} that are originally even? Wait, need to compute required flips. Let parity_orig(v) = deg(v) mod2. Desired parity for v: even for v not in {s,t}; odd for v in {s,t}. So we need to flip parity for v if orig parity != desired. So define T = {v : orig parity XOR desired parity = 1}. Then we need a T-join (minimum weight set of edges to make each vertex in T have odd count in added edges). For an Eulerian trail exists if we can achieve that T size is even (always) and we add edges accordingly. The total added edge weight is min weight of T-join, which equals min distance sum for pairing T. For closed CPP, T = O (all odd vertices). For open, we can choose s,t to minimize total added weight, giving min over all pairs (or all subsets) of the T-join weight with T = O Δ {s,t} (since we want to flip parity for O but keep s,t odd). Actually O Δ {s,t} is the set of vertices whose parity needs to be flipped (since if v is odd and not in {s,t}, we want even -> flip; if v is odd and in {s,t}, we want odd -> no flip; if v is even and in {s,t}, we want odd -> flip; if v is even and not in {s,t}, we want even -> no flip). So T = (O \ {s,t}) ∪ ({s,t} \ O). So T is symmetric difference. So the minimal added weight for open walk (with chosen s,t) is the minimum weight of a T-join, which equals the minimum total length of paths pairing up vertices in T (since we can duplicate edges). In metric complete graph, the minimum T-join weight is the minimum sum of distances for a matching on T (if we think of duplicating edges, we can simply take the shortest paths between paired vertices). Since the underlying graph is complete and edges have weights? Actually edge weights are distances? But in our case, when we duplicate an edge, the cost is the number of times we traverse that edge; we want to minimize total number of extra edges traversed beyond the required once per edge. However, the "weight" of duplicating an edge is just 1 per traversal (since each edge traversal adds one to total edge count). So the distance between any two vertices in terms of number of edges traversed is just 1 if we go directly? But when we add a duplicate edge, we need to actually traverse a path that covers those edges multiple times. In Chinese postman, we duplicate edges to make the graph Eulerian, meaning we will traverse those duplicated edges as part of the walk. The total number of traversals of each edge is 1 plus the number of duplications. The length of the walk = |E| + sum_{duplicated edges} (number of times we traverse that edge extra?). Actually if we duplicate an edge, we need to traverse it an extra time (i.e., we traverse it twice total). In terms of total edges traversed, it's |E| + total extra traversals. The extra traversals come from the matching: we add paths (could be single edges) that we will traverse twice? Wait, typical Chinese postman: For an undirected graph, we find a minimum weight set of edges to add (duplicate) so that all vertices become even. Then an Eulerian circuit exists on the multigraph, and its length (number of edges traversed) = |E| + weight of added edges (since each added edge is traversed exactly once as part of the Eulerian circuit? Actually in the multigraph, we have the original edges plus extra copies. The Eulerian circuit traverses each copy exactly once, so total traversals = |E| + number of added edges. So length = |E| + added edges. That's the closed walk minimal edges.
For an open walk, we can similarly have an Eulerian trail from s to t on a graph where after adding edges, degrees satisfy: all even except s and t odd. Then the Eulerian trail traverses each edge once (original and added). So total edges traversed = |E| + added edges. So minimal open walk length = |E| + min_{s,t} (min T-join weight with T = O Δ {s,t}).
Now, in our specific graph K_k, edges are unweighted (each traversal of an edge counts as 1). Distances between vertices are 1 (since directly connected). So any T-join can be realized by adding direct edges between paired vertices; each added edge contributes weight 1 per edge (since we duplicate that edge). So the min T-join weight = minimum number of edges to add, which equals ceil(|T|/2) *? Actually we need to pair up vertices in T and add a path between each pair; the cheapest is to pair them directly, so each pair contributes 1 (one edge) if we add that edge. However, careful: if we add a direct edge between u and v, that adds one extra traversal of that edge. But does that correctly change parity for both u and v? Yes, adding one edge incident to u and v flips parity of both. So each pair of vertices in T can be matched with one added edge. So the minimal number of added edges = |T|/2 (since T must have even size). So the added weight = |T|/2. So total edges traversed = |E| + |T|/2.
Thus, for K_k:
If k is odd: all degrees even, O = empty set. For closed walk, added edges = 0, so minimal edges = |E|. An Eulerian circuit exists; length = |E|+1 vertices. For open walk, we can choose s and t. To have an open Eulerian trail, we need exactly two vertices odd. Since all are even, we would need to make two vertices odd by adding a T-join with T = {s,t} (since O empty). That requires adding a path between s and t (with odd number of edges? Actually to flip parity of both s and t, we need to add a set of edges such that degrees of s and t increase by odd numbers. The cheapest is to add a single edge between s and t, which flips both (since each gets +1 degree). So added edges = 1. Then total edges = |E| + 1. But can we do better by not adding an edge? If we don't add any, all degrees even, only closed Eulerian circuits exist; but we want an open walk. However, we can still produce an open walk that covers all edges without being an Eulerian trail? For covering all edges, we need to traverse each edge at least once. For a graph that is Eulerian (all even), the shortest covering walk is not necessarily closed? We can consider an open walk that starts at one vertex and ends at another; to cover all edges, we might still need to duplicate some edges because an Eulerian circuit is closed; if we want an open walk, we could simply take an Eulerian circuit and remove the last edge? But then the last edge would not be traversed? Actually an Eulerian circuit is a closed walk that covers all edges exactly once. If we take a prefix of it of length L vertices (L-1 edges), we would miss the edges after that prefix. So not covering all. So we need to cover all edges; the minimal open walk might be obtained by taking an Eulerian circuit and then breaking it at some point, but that would still cover all edges exactly once, but the walk would be open? Wait, if we have an Eulerian circuit that starts and ends at v0, we can represent it as a sequence of vertices: v0, v1, v2, ..., v_{E}, where v_E = v0. This is a closed walk. If we instead start at v0 and end at v_{E-1} (i.e., omit the last step returning to v0), we would have traversed all edges except the last edge from v_{E-1} to v0. So we would miss that edge. To cover that edge, we need to include it somewhere else. So to have an open walk covering all edges, we could traverse all edges exactly once plus maybe an extra edge to start/end at different vertices. That would be an Eulerian trail on a graph where exactly two vertices are odd. In an Eulerian graph, if we add one extra edge, we make two vertices odd. Then there is an Eulerian trail that covers all edges (original plus extra) exactly once, starting and ending at the odd vertices. That trail, when we remove the extra edge? Actually the Eulerian trail would traverse the extra edge as part of the walk. So total edges traversed = |E|+1. But if we want the set of edges covered to be exactly the original edges (no requirement to cover extra edges? The condition only requires that each original edge appears at least once as adjacency; we are allowed to have additional adjacencies (i.e., extra edges) beyond the original ones. In the walk, we can include extra edges that are not needed for coverage. So we can construct a walk that covers all original edges exactly once, but also possibly includes extra edges. The Chinese postman approach minimizes the total length (number of edges traversed) to cover all original edges at least once. So the minimal open walk length (edges) would be |E| + extra, where extra is the minimum number of extra edges needed to make the graph have an Eulerian trail (open). As argued, for odd k (even degrees), we need to add at least one edge to have exactly two odd vertices. So extra >=1. Can we achieve exactly 1? Yes, add an edge between any two vertices (duplicate an existing edge). Then the multigraph has all vertices even except those two become odd (since each gets +1). Then there is an Eulerian trail covering all edges exactly once (including the duplicate). That trail has total edges = |E|+1. So minimal edges for open walk = |E|+1? But we need to confirm if an Eulerian trail exists with exactly one duplicate edge. After adding one duplicate edge between a and b, degrees: a and b increase by 1, making them odd if originally even; others even remain even. So exactly two odd vertices (a and b). Then an Eulerian trail exists from a to b. That trail traverses each edge exactly once, including the duplicate, so total edges = |E|+1. So minimal number of edges in a walk covering all original edges at least once is |E|+1? Could there be a walk that covers all original edges but uses fewer than |E|+1 edges? That would be less than total original edges, impossible because you need to traverse each original edge at least once, so number of edges traversed >= |E|. If you traverse exactly |E| edges, you must traverse each original edge exactly once, and no extra edges. But does there exist a walk of length |E| edges that traverses each edge exactly once in a graph with all even degrees? That would be an Eulerian circuit, which is closed. So the walk would have to be closed; but we can have a closed walk of |E| edges (starting and ending at same vertex) covering all edges exactly once. That's an Eulerian circuit. However, is a closed walk allowed? Yes, the array can start and end at any vertices; a closed walk is just a sequence where a1 = a_{n}? But that's allowed because we don't have restrictions on start/end. In our array, we only care about adjacencies; it can be any sequence. So a closed walk of |E| edges is a valid array of length |E|+1. That's a sequence of length n = |E|+1. So for odd k, we can achieve n = |E|+1 with a closed Eulerian circuit. That's minimal n? Could we achieve n = |E|? That would be |E| edges, but that would require traversing each edge exactly once, but the number of vertices would be |E|+? Actually a walk with e edges has e+1 vertices. So if we want n vertices, number of edges = n-1. To have n-1 = |E|, we need n = |E|+1. So the minimal n is exactly |E|+1. So for odd k, minimal array length to cover all edges of K_k is |E|+1 = k(k-1)/2 + 1.
Now for even k: All vertices have odd degree (k-1 odd). So O = all k vertices (k even). For closed walk: need to add a minimum perfect matching on O to make all even. Since k is even, we can pair up the k vertices. Each pair adds one edge (duplicate). So added edges = k/2. So total edges traversed = |E| + k/2. Then the closed Eulerian circuit length (vertices) = (|E| + k/2) + 1 = |E| + k/2 + 1.
For open walk: we can leave two vertices odd, so we need to add edges to change parity for the remaining k-2 vertices from odd to even (since they are odd, we want them even, so flip parity) and also possibly for the two odd we want them odd, so no flip. So T = O \ {s,t} (since we want to flip those). So |T| = k-2 (even). Minimal added edges = (k-2)/2 = k/2 - 1. Total edges = |E| + k/2 - 1. Then the open Eulerian trail length (vertices) = total edges + 1 = |E| + k/2.
So for even k, we have two possibilities: closed walk gives n = |E| + k/2 + 1; open walk gives n = |E| + k/2. Which is smaller? open gives n = |E| + k/2, closed gives +1 extra. So minimal n is |E| + k/2.
But is it always possible to achieve n = |E| + k/2? That would be an Eulerian trail on a graph where we added (k/2 - 1) duplicate edges (making all but two vertices even). Then the Eulerian trail covers all original edges exactly once plus the added edges once. The total vertices = edges+1 = |E| + k/2. So yes.
But could we achieve n = |E| + k/2 - something? Let's check if we can cover all edges with fewer than |E| + k/2 edges? Suppose we try to use a walk that is not Eulerian (i.e., some edges traversed multiple times, but maybe we can cover all edges with less than |E| + k/2 total edges? That would imply some edges are covered without being traversed? impossible, you must traverse each edge at least once. So total edges traversed >= |E|. For even k, original graph has all odd vertices. Any walk that starts and ends at vertices has odd-degree vertices? In a walk, the degrees of vertices in the multiset of traversed edges (counted with multiplicities) have parity: start and end vertices have odd degree (if you consider the degree in the walk, i.e., number of times the vertex appears as an endpoint of edges, each visit except start and end contribute 2). Actually in a walk, the number of times the walk enters a vertex equals the number of times it leaves, except start and end. So the parity of the count of incident edges in the walk for a vertex is: for start ≠ end, start has odd degree (edges count odd), end odd, others even. For start = end, all even. So the set of vertices with odd degree in the walk (counting traversals) is either empty (closed) or exactly two (open). When we require that the walk covers all original edges at least once, the multiset of traversed edges must include each original edge at least once. So the walk's edge multiset induces degrees that are at least the original degrees (since each original edge appears at least once). But parity conditions might force extra edges. In particular, for any vertex v, its total degree in the walk (d_w(v)) must have same parity as its degree in the original graph? Not necessarily, because we can add extra traversals of edges incident to v. d_w(v) = d_orig(v) + extra_incident(v). Since we can add extra edges arbitrarily, we can adjust parity. But the walk's parity constraints: if start≠end, d_w(v) even for all v except start and end (odd). If start=end, all even. So we need to add extra edges to the original edge set to satisfy these parity conditions. The minimal number of extra edges added is essentially the minimal size of a T-join where T = O (original odd vertices) for closed, or T = O Δ {s,t} for open. As argued, minimal extra edges = ceil(|T|/2) because we can pair vertices directly.
Thus minimal total edges traversed = |E| + min_{s,t?} ceil(|T|/2). For even k: |O| = k. For closed: T = O, size k -> extra = k/2. For open: we can choose s,t to minimize |T|. T = O Δ {s,t} = if both s,t in O, then T = O \ {s,t}, size k-2, extra = (k-2)/2 = k/2 -1. If one or both not in O, impossible because all vertices are in O? Actually all are in O, so if we choose s,t both in O, T = O \ {s,t} as above. If we choose s not in O? But O = all vertices, so any vertex is in O. So T = O \ {s,t} always. So extra = k/2 -1. So minimal total edges = |E| + k/2 -1. That yields n = |E| + k/2.
So the minimal n needed to accommodate a set S of size k is:
If k = 0? Not relevant.
If k = 1: Then there are no pairs, condition vacuously true. So any n >= 1 works. Minimal n = 1.
If k >= 2:
Let E = k(k-1)/2.
If k is odd: minimal n = E + 1.
If k is even: minimal n = E + k/2.
But wait: For k=2: k=2 is even. Then E = 1. Minimal n predicted = E + k/2 = 1 + 1 = 2. But can we have a beautiful array of length 2 using two distinct numbers? Need to have for pair (x,y), there exists an adjacent pair either (x,y) or (y,x). With length 2, we can set a1=x, a2=y or a1=y,a2=x. That covers the edge. So n=2 works. Also n=1? For k=2, we need both numbers to appear at least once. With n=1, impossible to have two distinct numbers. So minimal n=2. Our formula gives 2, ok.
For k=3: odd, E = 3, minimal n = 4. Is it possible to cover all three edges of K3 with a sequence of length 4? K3 vertices: 1,2,3. Edges: (1,2), (1,3), (2,3). We need all three unordered pairs appear as adjacent somewhere. Can we do with 4 elements? Example: 1,2,3,2? Check adjacencies: (1,2) yes, (2,3) yes, (3,2) gives (2,3) again? Actually (3,2) is the same unordered pair {2,3} already covered. But need (1,3). Not present. Sequence 1,2,3,1: adjacencies: (1,2),(2,3),(3,1) -> covers all three. Length 4. So n=4 works. n=3? Could we do with 3? Sequence of length 3 has 2 adjacencies. With three vertices we need to cover 3 distinct unordered pairs, impossible. So minimal n=4. Good.
k=4: even, E=6, k/2=2, minimal n = 6+2 = 8. Let's test: can we have a beautiful array of length 8 covering all 6 edges of K4? Possibly. Sequence of length 8 means 7 adjacencies. Minimum extra edges = k/2 -1 = 1? Actually total edges traversed = 6 + (k/2 -1) = 6+1=7, so n = 8. Could we do with n=7? That would be 6 edges, total traversals =6, meaning we traverse each edge exactly once. That would require an Eulerian trail that covers each edge exactly once. But for k=4 (even), all vertices odd, so we would need to have exactly two vertices odd in the walk. But if we traverse each edge exactly once, then the degree of each vertex in the walk is exactly its original degree (since each edge incident contributes 1). Original degree =3 (odd) for each vertex. So in the walk, all four vertices would have odd degree, which is impossible for a walk (since walk has either 0 or 2 odd-degree vertices). So we need at least one extra edge to adjust parity, so total edges at least 7. So n=8 minimal. So formula seems correct.
k=5: odd, E=10, minimal n=11. Check: Eulerian circuit exists (since all degrees even, degree=4 even). So can we do with n=11. Could n=10? That would be 9 edges, less than total edges 10, so impossible. So minimal n=11.
So minimal n for a set of size k (k>=2) is:
n_min(k) = k(k-1)/2 + (0 if k odd? Actually plus 0? For odd, n_min = E+1 = k(k-1)/2 + 1.
For even, n_min = E + k/2 = k(k-1)/2 + k/2 = k(k-1+1)/2 = k^2/2. Wait compute: k(k-1)/2 + k/2 = (k(k-1) + k)/2 = (k^2 - k + k)/2 = k^2/2. So for even k, n_min = k^2/2. For odd k, n_min = k(k-1)/2 + 1 = (k^2 - k + 2)/2. Simplify: (k^2 - k + 2)/2. For odd k, k^2 is odd, so (odd - odd + even)/2 => integer? Yes.
Thus we have a condition: Given n (array length), we can include a set S of distinct numbers (coupon numbers) of size k only if n >= n_min(k). Also, if n is larger than n_min(k), we can always extend the array by repeating elements arbitrarily? We must ensure that adding extra elements does not break the beautiful condition, and we also must ensure that we don't introduce new pairs? Actually if we add extra occurrences of numbers already in S, we don't introduce new distinct numbers, so the set of distinct numbers remains S. The beautiful condition only cares about the set of numbers present. Adding extra elements (repetitions) does not create new pairs, and it doesn't remove existing adjacencies, so the condition remains satisfied as long as we preserve the existing adjacencies that cover all pairs. But we must be careful: If we insert extra elements in the middle, we might break some adjacencies? But we can always extend the array by repeating a number at the end, for example, appending the last element multiple times. That will not affect existing adjacencies; it adds new adjacencies that are (last, last) which are not relevant for pairs of distinct numbers (x≠y). So still all pairs are covered. Similarly, we could prepend. So as long as we have a base array of length n_min(k) that satisfies the condition, we can pad to any larger length by repeating a single element (or any method) without violating condition. So the feasibility condition for a set S of size k is simply: n >= n_min(k). (For k=0? Not considered; we need at least one number because array length n >=1, but k=0 is impossible because array must have elements. However, we could consider k=0 not allowed. So min k=1.)
Thus the problem reduces to: We have m coupons, each with value wi. We want to select a subset of coupons (i.e., a set of numbers) to include in the array, maximizing total sum of wi, subject to the condition that the size of the subset, k = |S|, satisfies n >= n_min(k). Since we can always include any subset of size k if n >= n_min(k). But note: we are not forced to use exactly those numbers; we could also include numbers from coupons not in S? No, we only pay for numbers that occur. So we choose S to be exactly the set of numbers that appear. So we must be able to construct a beautiful array of length n that uses exactly the numbers in S (each at least once). As argued, as long as n >= n_min(|S|), we can construct such an array. However, is there any additional constraint regarding which specific numbers? The condition depends only on pairs being covered, not on the actual values, so any set of distinct numbers of size k works as long as we can arrange them to cover all edges. Since we have complete graph on k labels, it's purely combinatorial; the labels are irrelevant. So feasibility depends solely on k.
Therefore, the maximum total sum is simply: among all possible k (0? 1 up to m) such that n >= n_min(k), we want to choose the k coupons with the largest wi values? Because we can choose any subset; to maximize sum, we would pick the coupons with highest wi, since all coupons are available (they have distinct qi, but that doesn't matter). The only restriction is the number of distinct numbers we can include, i.e., the size k. Since we can pick any k numbers, we obviously pick those with the largest w_i. So the answer is: sort wi in descending order, compute prefix sums, and find the maximum prefix sum for k such that n >= f(k), where f(k) = minimal required length.
But we must also consider the case k=0? Not relevant, since n>=1 and we need at least one number; but maybe we could choose empty set? Then array would have no numbers? Not possible. So k>=1.
Edge cases: n could be huge (up to 2e6), but m up to 1e5. k can be up to m (1e5). But n_min(k) grows quadratically: for k large, n_min(k) ~ k^2/2. Since n max is 2e6, the maximum feasible k is such that k^2/2 <= 2e6 => k^2 <= 4e6 => k <= 2000 approximately. Indeed sqrt(4e6)=2000. So feasible k is at most around 2000. Because for odd k, n_min ~ (k^2 - k + 2)/2 < k^2/2 + something, still roughly k^2/2. So k max is about 2000. So we can compute f(k) for k up to maybe while f(k) <= n, but k may be up to m=1e5, but we only need to consider k up to some limit where f(k) <= n. Since n <= 2e6, f(k) grows quickly, so the maximum k is about O(sqrt(n)). So we can precompute f(k) for k from 1 up to, say, 3000 or until f(k) > n, then we know the maximum possible k.
But careful: The condition for k=1: n_min(1)=1, always satisfied for n>=1. So we can always take at least one coupon. For k=0 not allowed.
Thus algorithm:
Read n, m.
Read m pairs (qi, wi). We only need wi. (qi distinct but irrelevant.)
Sort wi in descending order.
Compute prefix sums: pref[i] = sum of top i wi (i from 1 to m).
For k from 1 to m, if f(k) <= n, candidate sum = pref[k]; take maximum over such k.
Output that maximum.
But is it always optimal to take the top k wi? Could there be a scenario where we skip a high wi to include more numbers? That would reduce sum, not increase. Since all wi are positive? wi are >=1? The constraints: 1 <= wi <= 10^5, so positive. So sum is increasing with more numbers if all positive. So to maximize sum, for a given k, we want the largest k wi. So yes.
But wait: Could there be a scenario where we might want to not include some high wi because it forces a larger k which requires higher n_min and maybe we can't achieve that k due to n, but we can still include that high wi by itself? Actually if we want to maximize sum, we consider all possible k; for each k, we pick top k wi. Among those k, the sum increases as k increases (since all wi positive). So the maximum sum will be achieved for the largest feasible k (since adding more positive numbers increases total). However, is the prefix sum necessarily monotonic increasing? Yes, because wi positive. So the maximum total sum is simply pref[k_max] where k_max is the maximum k such that f(k) <= n. But careful: Could there be a case where a larger k is feasible but its prefix sum is not necessarily larger than a smaller k if we skip some low wi? But since we are forced to include exactly k numbers if we choose size k, and we can choose any set, the best sum for size k is the sum of the k largest wi. As k increases, this sum strictly increases because we add another positive wi (the k-th largest). So indeed, the maximum over k is attained at the maximum feasible k. So answer = sum of largest k_max wi, where k_max = max{k | f(k) <= n}.
But need to double-check monotonicity: f(k) is increasing with k? Likely yes. Check: f(1)=1, f(2)=2, f(3)=4, f(4)=8, f(5)=11, f(6)=18,... It is increasing? Let's verify differences: from 2 to 3: 2->4 increase; 3->4:4->8 increase; 4->5:8->11 increase; 5->6:11->18 increase. So yes, increasing. So the feasible k's form an interval from 1 to some max. So answer is sum of top k_max wi.
But hold on: There might be nuance: The array length n might be less than f(k) for certain k, but we could still include those k numbers if we don't require that all pairs are covered? But the condition must be satisfied. So we must have all pairs covered. So indeed we need f(k) <= n.
But is f(k) exactly the minimal length? We should confirm for k=1: n_min=1. Good.
For k=2: n_min=2.
For k=3: 4, as we saw.
For k=4: 8.
For k=5: 11.
For k=6: 18.
Let's test k=6: According to formula even: k^2/2 = 36/2=18. Minimal edges = 15, extra = 3 (since k/2 =3). Could we do with n=17? That would be 16 edges, which is 1 less than 18? Actually total edges = n-1. For n=17, edges=16. We need to cover 15 edges at least once. So total edges must be at least 15, but also parity constraints: For k=6 (even), we need at least 1 extra edge beyond 15? Let's compute minimal extra edges: For open walk, we need extra = k/2 -1 = 2? Wait for even k, we gave two options: closed requires extra = k/2 =3, open requires extra = k/2 -1 =2. But we argued open gives total edges = |E| + (k/2 -1) = 15 + 2 = 17 edges, so n = 18? Actually edges+1 = n, so n = 17? Let's recalc: open total edges = |E| + (k/2 -1) = 15 + 2 = 17. Then n = total edges + 1 = 18? Wait: number of vertices = number of edges + 1. So if total edges traversed = 17, then n = 18. That matches n = |E| + k/2 = 15 + 3 = 18? No, careful: |E| = 15. For open walk, we said total edges = |E| + (k/2 -1) = 15 + (3-1)=17. Then n = 17+1 = 18. But earlier I computed n = |E| + k/2 = 15+3=18. So consistent: n = |E| + k/2. So for k=6, n_min=18. Could we achieve n=17? That would be total edges 16. To have total edges 16, we need to cover 15 distinct edges, so one extra edge only (since 16-15=1). That means extra edges =1. Does that satisfy parity? For k=6, all vertices odd. After adding 1 extra edge (say between a and b), the degrees become: a and b now have degree 3+1=4 (even), others have degree 3 (odd). So odd vertices = 4 (since 4 vertices remain odd). For a walk, we need either 0 or 2 odd-degree vertices in the traversed multiset (counting multiplicities). But we also have the original edges each once plus the extra edge once. So the degree multiset (in the walk) will be original degree + contribution from extra edge. That gives 4 odd vertices. That's not possible for a walk (which requires 0 or 2 odd vertices). So we need to add at least enough extra edges to reduce the number of odd vertices to 0 or 2. The minimum number of extra edges to reduce from 6 odd to 2 odd is (6-2)/2 = 2 edges? Actually each added edge flips parity of its two endpoints. To go from 6 odd to 2 odd, we need to flip 4 vertices to even, i.e., pair them up, requiring 2 edges. So extra edges = 2, total edges = 17, n = 18. So indeed n=17 not feasible. So formula stands.
Thus answer is sum of largest k_max wi where k_max = max k with f(k) <= n.
But we must also consider that we might not need to include all numbers of the chosen set exactly k. Could we include a set of size k but also include some other numbers that are not in S? Not allowed because only coupon numbers allowed. So S is exactly the set of distinct numbers in array.
Now, is there any possibility to have a set of size k but with n less than f(k) by cleverly not requiring to cover all pairs? Wait condition says: for each pair x,y (x≠y) that occur, there must exist an adjacent occurrence of that pair (in either order). So it's mandatory. So we cannot skip any pair. So we must cover all pairs. So minimal length is indeed f(k).
But we should verify that f(k) is achievable for all k. We need to construct a sequence of length exactly f(k) that covers all pairs. For odd k, Eulerian circuit gives length E+1 = f(k). For even k, open Eulerian trail gives length E + k/2 = f(k). So it's achievable. So the condition is tight.
Thus the problem reduces to simple calculation.
But wait: There is also the possibility of using numbers from coupons with zero cost? All wi positive? Minimum is 1, but maybe could be zero? Input says 1 ≤ wi ≤ 1e5, so positive.
Now, is there any nuance about the array length n being extremely large (2e6) and m up to 1e5, but k_max maybe only around 2000. So we only need top ~2000 wi. However, sorting m=1e5 numbers is fine (O(m log m)). Then compute prefix sums up to m. Then find k_max by iterating k from 1 upward until f(k) > n, but we need to be careful about overflow when computing f(k) for k up to maybe 2000, but using 64-bit is fine.
But we must also consider k=0? Not needed.
Now test sample 1: n=5, m=2, wi = [2,3] sorted descending = [3,2]. Compute f(1)=1 <=5; f(2)=2 <=5; f(3) would be >5 but m=2 so max k=2. So answer = 3+2=5. Matches.
Sample 2: n=100, m=3, wi = [2,1,1] sorted descending = [2,1,1]. f(1)=1; f(2)=2; f(3)=4? Wait k=3 odd => f(3)=3*2/2 +1 =3+1=4? Actually E=3, f(3)=4 <=100; f(4)=8 <=100; f(5)=11 <=100; ... But m=3, so max k=3. Sum=2+1+1=4. Output 4. Good.
Sample 3: n=1, m=2, wi = [1,100] sorted = [100,1]. f(1)=1 <=1, so k_max=1? But f(2)=2 >1, so k_max=1. Sum=100. Output 100. Good.
So matches.
Now, we should double-check the derivation for k=1. The condition vacuously holds; we can have any array of length n containing only that number. So f(1)=1.
One more test: n=2, m=3, wi = [5,4,3] sorted = [5,4,3]. f(1)=1 <=2; f(2)=2 <=2; f(3)=4 >2. So k_max=2, sum=5+4=9. Could we do better by using only the highest wi 5? That's 5, less. So answer 9. Is it feasible? n=2, set size=2, need both numbers appear and adjacent pair exists. With length 2, we can have [x,y] covering the pair. So yes. So answer 9.
Now, is there any scenario where we might want to not take the maximum possible k because the sum of the top k_max wi might be less than sum of top k for some smaller k? Since wi positive, prefix sums increasing, so larger k always gives larger sum. So yes.
But wait: Could there be a scenario where some wi are negative? The constraints say wi >=1, so positive. So fine.
Thus the solution is straightforward.
But we must ensure that f(k) formula is correct for all k, especially large k up to sqrt(2e6) ~ 2000. However, we need to compute f(k) = if k == 1: 1; else if k % 2 == 0: kk//2; else: (kk - k + 2)//2. Let's verify for k=1: odd case formula gives (1-1+2)/2=2/2=1, good. So we can use unified formula: for k>=1, f(k) = (kk + (k%2? 2 - k : 0))//2? Actually easier: if even: kk//2; if odd: (k*k - k + 2)//2.
Now, we need to consider if m is less than the theoretical max feasible k, then k_max = m obviously. So final answer is sum of all wi (if all can be included). But m up to 1e5, but n_max 2e6, so if m is huge (like 1e5) but n is also huge? But n max is 2e6, so even if n=2e6, k_max is about 2000, which is less than 1e5. So we will take at most 2000 top wi. So we can sort and take prefix.
But careful: n could be 2e6, f(k) for k=2000: if even: 2000^2/2 = 4e6/2? Wait 2000^2 = 4,000,000. Half = 2,000,000. So f(2000)=2,000,000. That's exactly n if n=2e6. For k=2001 (odd): compute (2001^2 -2001+2)/2 = (4,004,001 -2001 +2)/2 = (4,002,002)/2 = 2,001,001 > 2e6. So k_max could be 2000. So indeed max k is around 2000.
Now we need to compute prefix sum up to k_max. Since m can be up to 1e5, but we only need top up to maybe 2000, we could use nth_element or partial sort to get top k_max elements efficiently, but sorting full m is okay (1e5 log 1e5 ~ fine). So overall solution is O(m log m).
But wait, there's a nuance: The array length n can be as low as 1, and m up to 1e5. Then k_max is 1. Then answer is max wi. That's fine.
Thus the solution seems trivial. But before finalizing, let's double-check the problem statement for any subtlety: "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." So Dima chooses the array, but Sereja wants to maximize the amount he pays. So Dima will try to make Sereja pay as much as possible? Actually the problem says: "Sereja wants to build a beautiful array a" but then says "But not everything is so easy, Sereja's friend Dima has m coupons ... 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." So Sereja is worried about the maximum he might have to pay, i.e., given that Dima can construct any beautiful array using the coupon numbers (since he has coupons), what is the maximum total cost Sereja could be charged? So we need to compute maximum possible sum of wi for distinct qi used. Since Dima chooses the array, he will try to maximize the sum (since he gets money). So indeed we need to compute the maximum possible sum given constraints. So we assume Dima will select a set S (of numbers to include) that maximizes sum of wi, and then construct a beautiful array of length n using those numbers. So it's exactly our interpretation.
Now, confirm that Dima can use numbers from coupons without limit, i.e., he can use any number of occurrences of those qi. So yes.
Now, verify that Dima cannot use numbers not in coupons. It says "allows you to use as many numbers qi as you want", but it doesn't explicitly say that other numbers are forbidden. However, "Sereja has no coupons" so Dima has the coupons; it's implied that to use a number you need a coupon, otherwise you can't? Typically in such problems, the coupons give the right to use that number. Since Sereja has none, only numbers from coupons can be used. So we are correct.
One more nuance: The array must consist of integers. Could we use a number qi that is not in coupons if we don't pay? The deal is: Dima takes wi rubles for each qi which occurs. If qi is not a coupon, there is no wi associated; maybe Dima could use it for free? But the problem says "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." So the coupons are like licenses: to use a number, you need the coupon. Since Dima has them, he can use those numbers. He doesn't have coupons for other numbers, so he can't use them. So array only contains numbers from {qi}.
Thus solution stands.
But wait: Sample 2: n=100, m=3, wi: 2,1,1. According to our reasoning, k_max = max k with f(k) <= 100. Let's compute f(1)=1, f(2)=2, f(3)=4, f(4)=8, f(5)=11, f(6)=18, f(7)=? For odd: (49-7+2)/2=44/2=22, f(8)=64/2=32, f(9)= (81-9+2)/2=74/2=37, f(10)=100/2=50? Actually even: 10^2/2=50, f(11)= (121-11+2)/2=112/2=56, f(12)=144/2=72, f(13)= (169-13+2)/2=158/2=79, f(14)=196/2=98, f(15)= (225-15+2)/2=212/2=106 >100. So k_max = 14 (f(14)=98) or maybe 15? f(15)=106 >100, so k_max=14. But m=3, so effectively k_max=3. So sum=4. That matches.
Thus overall answer is sum of top min(k_max, m) wi.
Now, note: we need to consider the case where n is very small, like n=1, then k_max=1. So answer is max wi.
Now, we must be careful about 64-bit integer for sum: wi up to 1e5, k up to ~2000, sum up to 2e8, fits in 32-bit, but n up to 2e6 not needed for sum. But safer to use 64-bit.
Now, confirm with another example: n=8, m=5, wi = [10,9,8,7,6]. k_max? f(1)=1, f(2)=2, f(3)=4, f(4)=8, f(5)=11>8, so k_max=4. Sum of top 4 = 10+9+8+7=34. Could we actually achieve k=4 with n=8? f(4)=8 exactly, so yes. So answer 34.
Now, test edge: n=2, m=100, top two wi sum. So fine.
Now, ensure we have no off-by-one: For k=2, f(2)=2. Is there any requirement that for pair (x,y) we need an adjacent occurrence. With array length 2, we can have [x,y] covering the pair. So fine.
For k=3, f(3)=4. Is there a sequence of length 3 that covers all three pairs? Let's attempt: length 3 has two adjacencies. To cover three pairs, impossible. So minimal is 4. So correct.
Now, what about k=0? Not allowed.
Now, could there be a scenario where we can include a set of size k but not necessarily cover all pairs because we might be able to arrange the array such that some pairs are covered by the same adjacency? No, each adjacency covers exactly one unordered pair. So need at least as many adjacencies as pairs, i.e., n-1 >= number of pairs = k(k-1)/2. That gives n >= k(k-1)/2 + 1. That's a lower bound. But we also have parity constraints which might raise it further for even k. Indeed for even k, the bound n-1 >= E is necessary but not sufficient; parity forces extra edges, making n-1 >= E + (k/2 - 1) = E + k/2 -1. So n >= E + k/2. That matches our formula.
Thus solution is derived.
Now, implement: read n,m; vector w(m); for i in 0..m-1 read qi, wi; ignore qi. Sort w descending (or ascending then take suffix). Compute prefix sums. Then iterate k from 1 to m, compute required = f(k) and if required <= n, update answer = pref[k] (since pref is sum of top k). Since pref increases with k, we can break when required > n, and answer will be pref[previous k]. But careful: there may be larger k that are still <= m but f(k) > n; we stop. However, due to monotonicity of f, once f(k) > n, all larger k also > n. So break. So we can just find the maximum k.
But note: f(k) might be computed for k up to m, but m can be 1e5, but we break early because f(k) quickly exceeds n. So we can loop k from 1 upwards until either k > m or f(k) > n. But we need to compute f(k) each step. Complexity O(min(k_max, m)) which is at most ~2000, trivial.
However, we must ensure that we handle the case where m is huge but n small, so k_max may be small (<2000). So loop is fine.
But careful: we need to compute f(k) correctly for large k (like 1e5) if we loop without break? But we break when f(k) > n, so we won't loop many. Since f(k) grows quadratically, for n=2e6, k_max ~2000, so loop up to 2000. So fine.
Alternatively, we could compute k_max directly by solving k^2/2 <= n for even, but due to parity alternating, we can compute precisely by iterating or solving inequality. Iterating is simpler and safe.
But caution: for n up to 2e6, k_max could be as high as about 2000; iterating up to 2000 is fine. But what if n is huge? Actually constraint is n ≤ 2·10^6, so at most 2e6. So k_max is bounded by about 2000. So loop up to 2000 is fine.
But wait, what if m is less than 2000? Then we need to loop up to m.
So overall algorithm:
Read n, m.
Create array w of length m.
For each coupon, read qi and wi; store wi.
Sort w in non-increasing order.
Compute prefix sums array pref (size m+1, pref[0]=0). Or just keep running sum.
Initialize max_sum = 0.
For k from 1 to m:
if k == 1: need = 1 else if k%2==0: need = kk//2 else: need = (kk - k + 2)//2
if need > n: break
max_sum = pref[k] (or keep as variable)
Output max_sum.
But need to be careful: For k=1, the formula for odd gives (1-1+2)/2 = 1, works, so we can just use the unified formula for all k>=1: need = (k*k + (k%2 ? (2 - k) : 0)) // 2. But simpler to use conditional.
Now, double-check f(2): even: 2*2/2=2, correct.
Thus answer.
But we must consider if n is 0? No, n >= 1.
Edge: n could be 2,000,000, and k_max could be 2000 exactly, but we need to compute 2000^2 = 4,000,000, which fits in 32-bit int? 4e6 < 2^31, fine. Use 64-bit for safety.
Now, test with maximum: n=2000000, m=100000, wi random. We compute top k_max about 2000. Sorting 100k is fine.
But is there any chance that we could include more than k_max numbers by not covering some pairs? No, condition is strict.
But wait: Could there be a possibility to include numbers such that some pairs are not required because they don't both occur? Actually condition says: consider all pairs x,y (x≠y) such that both occur. So if we include numbers, all pairs must be covered. So no.
Now, confirm for k=1: f(1)=1. Good.
Now, final step: Ensure we use 64-bit for sum, but int is fine as max sum is 1e5 * 2000 = 2e8, fits in 32-bit signed (2.1e9). But still safe to use long long.
Now, any other nuance? Could Dima choose to not use a coupon number even though he has it? Yes, he chooses the array. So he can decide to include or not include each qi. So he will include the ones with highest wi as long as feasible.
Thus answer.
But wait: The problem statement says: "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." It might be interpreted as: For each coupon i, if qi appears in the array, Sereja pays wi (regardless of how many times). So per distinct qi. So correct.
Now, let's check for n=0? Not allowed.
Now, I'd like to verify with some random small cases by brute force to ensure formula works. But given reasoning seems solid.
However, I realize there might be another angle: The adjacency condition must be satisfied for each pair (x,y) with x != y. Could it be satisfied by a single occurrence of an adjacency that is (x,y) OR (y,x). So we need at least one directed adjacency. In a sequence, each adjacency contributes one unordered pair. So we need at least as many adjacencies as unordered pairs. That's n-1 >= k(k-1)/2. But we also need that it's possible to have a sequence with exactly that many adjacencies covering all pairs. That's like constructing a walk that covers all edges of K_k. The minimal number of edges in such a walk is what we derived via Eulerian considerations.
But is it always necessary to have extra edges beyond E for even k? Could we design a sequence of length E+1 (i.e., n = E+1) for even k? That would be edges = E. That would mean traversing each edge exactly once. This is an Eulerian trail? But for even k, all vertices have odd degree, so sum of degrees = E*2 is divisible? Actually sum of degrees in the walk (counting each traversal) would be 2E. The degree of each vertex in the walk is the number of times edges incident are traversed. If we traverse each edge exactly once, then degree of vertex v = original degree = k-1, which is odd. Then the walk would have all k vertices odd-degree. In any walk, the number of odd-degree vertices is either 0 or 2 (since start and end vertices have odd parity if distinct, or all even if closed). So having k odd-degree vertices with k>2 is impossible. So we need to traverse some edges at least twice to fix parity. So indeed we need extra edges.
So the formula stands.
Now, I think the solution is correct.
But wait: There's another possibility: Could we use the array to cover pairs in a way that is not a simple walk on the complete graph? Because we can have repeated vertices, but the edges are undirected pairs. The walk must cover each edge at least once. The constraints on walk parity are fundamental: In any walk (sequence of vertices), the number of vertices with odd degree (count of incident traversed edges) is either 0 (if closed) or 2 (if open). This is because the degree of a vertex equals the number of times it appears internally times 2 plus possibly 1 for start and 1 for end. More formally, for a sequence a1..an, define degree d(v) = number of i from 1 to n-1 such that ai=v or a_{i+1}=v? Actually each occurrence of v in interior contributes 2 to degree (one from incoming, one from outgoing), except the first and last vertices contribute 1 each. So sum of degrees = 2(n-1). The parity of d(v) is: d(v) mod2 = (count of times v appears as first or last) mod2. So there are either 0 odd-degree vertices if first=last, else exactly 2 odd-degree vertices (first and last). So indeed.
Thus the parity condition is necessary.
Therefore, the minimal n is as given.
Now, we should also consider if there is a possibility of using a set S with size k but not necessarily requiring to have all edges because we could arrange the array so that some pairs are covered by the same adjacency? That's not possible; each adjacency covers exactly one unordered pair.
Thus the solution stands.
Now, one more nuance: The array a consists of integers. Could we use numbers that are not from coupons but have wi=0? No, coupons have wi>0, and if we use a number not in coupons, Sereja would not pay anything, and Dima wouldn't gain. But maybe Dima could include such numbers to help satisfy the beautiful condition without increasing cost? For example, if we need to cover many pairs, we might use extra numbers as "connectors"? But the condition only cares about pairs of numbers that occur. If we introduce an extra number (not a coupon), then that number occurs, and it must pair with every other number that occurs (including coupon numbers). That would increase the set of distinct numbers, thereby increasing the number of pairs that need to be covered, making it harder. Also, we don't gain any wi for that number. So Dima would not want to include extra numbers because they increase the requirements without adding payment. So optimal is to use only coupon numbers.
But could it be beneficial to include a coupon number with low wi if it helps to reduce the required length for a given set of high-wi numbers? For example, maybe by including an extra number, we could reduce the minimal n required to include a certain set of high-wi numbers? But including an extra number increases k, which increases minimal n. So not beneficial. So Dima will only include numbers that contribute positively to sum; i.e., any number included must have positive wi (since all wi are positive). Including additional numbers always increases the required n, but if we have slack in n, we might include more numbers to increase sum. So we want to maximize sum given n, which is to include as many numbers as possible (with highest wi) until we hit the n limit.
Thus the greedy selection of top wi up to k_max is optimal.
Now, implement.
But wait: Could there be a scenario where we choose a set S of size k, but we cannot construct an array of length exactly n (n > f(k)) because the extra padding might disrupt the beautiful property? We argued we can always pad by repeating an element. But we must ensure that repeating an element does not break any existing pair coverage. Adding an element at the end (or beginning) by repeating the last (or first) element adds an adjacency of (last, last) which is not a pair of distinct numbers, so doesn't affect. Also, we could insert repetitions in the middle, but that might split existing adjacencies. However, we can always pad by appending copies of the last element, as that does not remove any existing adjacency. For example, take the minimal array of length f(k) that is beautiful. Then extend it to length n by adding extra copies of the last element at the end. The new adjacencies are between the last element (say x) and itself, which are irrelevant for distinct pairs. All original adjacencies remain. So the condition still holds. Similarly, we could prepend copies of the first element. So padding is safe. So for any n >= f(k), we can construct a beautiful array using exactly the same set S. So feasibility depends only on n >= f(k).
Thus solution stands.
Now, consider k=0? Not allowed.
One more thing: For k=1, f(1)=1. But if n is large, we can have array of all that number. So fine.
Now, let's think about the possibility that some qi may be the same as another? They are distinct, so no.
Now, implement.
But before coding, double-check with some random test using brute for small n, k to confirm f(k) indeed minimal.
We can do a quick mental verification for k=4, n=7? According to formula, n_min=8, so n=7 should not be feasible. Could there be a sequence of length 7 covering all 6 pairs of K4? Let's attempt: Need 6 edges covered, sequence length 7 gives 6 adjacencies. So we must cover each of the 6 edges exactly once. That would be an Eulerian trail? But as argued, K4 has all vertices odd (degree 3). To have a trail covering each edge exactly once, we need exactly 0 or 2 odd-degree vertices in the multiset of traversed edges. But if we traverse each edge exactly once, each vertex degree =3 (odd), so 4 odd vertices, impossible. So not possible. Could we cover all edges with 6 adjacencies but some edges covered more than once? That would mean some edge covered twice, then some edge not covered, because total adjacencies is 6. So if we duplicate one edge, we miss another. So impossible. So n=7 not feasible. So correct.
Now, for k=5, n=10? f(5)=11, so n=10 not feasible. n=10 gives 9 adjacencies, need cover 10 edges, impossible. So fine.
Now, ensure we have considered k=1: n=1 works.
Now, finalize.
Now, I'll produce a solution in C++.
Implementation steps:
Use scanf/printf or cin/cout? The problem advises not to use %lld but use cin/cout or %I64d. We'll use cin/cout with ios::sync_with_stdio(false) for speed.
Read n,m.
vector w(m).
for i in 0..m-1: read qi, wi; w[i]=wi.
sort w.begin(), w.end(), greater())
long long ans = 0, sum=0.
for (int k=1; k<=m; k++) {
sum += w[k-1];
long long need;
if (k%2==0) need = 1LL * k * k / 2;
else need = (1LL * k * k - k + 2) / 2;
if (need <= n) ans = sum;
else break;
}
cout << ans << endl;
But careful: For k=1, else part: (1*1 -1 +2)/2 = 2/2=1; fine.
Now, test with sample.
Now, think about overflow: k up to maybe 2000, k*k up to 4e6, within 32-bit, but using long long safe.
Now, but what if n is very large, say 2e6, and m small, k could be up to m which may be up to 1e5, but we break once need > n, which will happen for k about sqrt(2n) ~2000, so we won't iterate up to 1e5. So safe.
Now, one more nuance: The coupon numbers are distinct, but we don't care. So fine.
Now, let's consider if there is any scenario where we could achieve a set of size k with n slightly less than f(k) by not requiring to cover all pairs because we could use the fact that the condition is "for each pair x,y, there exists some position j such that either aj = x, aj+1 = y OR aj = y, aj+1 = x." It does not require that the adjacency occurs between distinct occurrences? Actually it does, because it says x≠y, and both occur. So we need an adjacency with those two distinct numbers. That's it. So we need at least one adjacency for each unordered pair.
Now, is it possible to cover multiple unordered pairs with a single adjacency? No, because an adjacency involves exactly two (possibly equal) numbers, but x≠y so they are distinct, so one adjacency corresponds to exactly one unordered pair. So number of adjacencies must be at least number of unordered pairs.
Thus lower bound: n-1 >= k(k-1)/2.
Now, could we have a sequence where the number of distinct unordered pairs covered is more than n-1? Not possible.
Now, the parity argument gave an extra constraint for even k: n-1 must be at least E + (k/2 - 1). Let's derive that constraint directly: For a walk covering all edges of K_k, the multiset of traversed edges has certain degrees. Let d(v) be total traversals incident to v. Then sum_v d(v) = 2L where L = n-1. Also d(v) ≥ deg_K(v) = k-1. Let excess e(v) = d(v) - (k-1) ≥ 0, integer. Then sum_v e(v) = 2L - k(k-1). Since L = n-1, sum e(v) = 2(n-1) - k(k-1). The parity condition: number of vertices with odd d(v) is either 0 or 2. Since d(v) = (k-1) + e(v). Since k-1 parity: if k odd, k-1 even, so parity of d(v) = parity of e(v). If k even, k-1 odd, so parity of d(v) = opposite of parity of e(v) (i.e., (odd + e(v)) mod2 = 1⊕(e(v) mod2)). So we need to choose nonnegative integers e(v) such that sum e(v) = 2(n-1) - k(k-1) and the number of vertices where e(v) mod2 is something is constrained. For odd k: need vertices with odd e(v) count = 0 or 2 (since d(v) odd iff e(v) odd). For even k: need vertices with odd e(v) count = 0 or 2? Since d(v) odd when e(v) even? Actually if k even, k-1 odd, then d(v) mod2 = (1 + e(v)) mod2 = 1 xor (e(v) mod2). So d(v) odd when e(v) even. So the number of vertices with d(v) odd equals number of vertices with e(v) even. We need that number to be 0 or 2. So we need the number of vertices with e(v) even to be 0 or 2. That's equivalent to number of vertices with e(v) odd to be k or k-2 respectively. So constraints.
But we derived minimal L by setting e(v) as small as possible (mostly zeros) and adjusting parity by adding 1 to some vertices (by adding extra edges). The minimal total excess sum is the minimum needed to satisfy parity. That minimum is: if k odd: 0 if we want 0 odd? Wait, for odd k (k odd => k-1 even). All original degrees even. So if we set e(v)=0 for all, d(v)=even, so all even -> closed walk possible? But then L = E? But we need L = number of edges traversed. If e(v)=0, then total edges = E, but then the walk would have to be an Eulerian circuit, which is possible only if the graph is Eulerian (which it is for odd k). That yields L=E, n=E+1, and closed (all even). So excess 0 works. For open walk, we could have exactly two odd d(v) by making e(v) odd at exactly two vertices? Since d(v) even originally, to get odd d(v) we need e(v) odd for those two. That would require at least 1 excess per those two vertices. But the minimal sum e(v) to get two vertices odd is 2? Actually if we set e(v)=1 for two vertices, sum excess =2. That would add at least 1 extra edge? Because each excess of 1 at a vertex means we need to add an extra edge incident to that vertex. To increase e(v) by 1 at two vertices, we can add one edge between them, giving +1 to each. That's excess sum =2. So L = E+1, n=E+2? Wait, sum excess = 2 leads to 2L - k(k-1) = 2 => 2L = k(k-1)+2 => L = E + 1, n = L+1 = E+2. But earlier we thought minimal open for odd k was n = E+2? Actually earlier we said open requires adding one edge, giving total edges = E+1, n = E+2. But we previously thought minimal n for odd k was E+1 from Eulerian circuit. But open would be larger. But we are free to choose either closed or open; we want minimal n overall, so we take closed (E+1). So minimal n is E+1 for odd k. So that's consistent.
For even k: original degrees odd. To achieve all even (closed), we need to flip parity of all k vertices from odd to even. That requires e(v) odd for each vertex? Because d(v) = odd + e(v). To make d(v) even, e(v) must be odd. So need e(v) odd for all k vertices. The minimal excess to make e(v) odd for all is at least 1 per vertex, but we can pair them with edges: each added edge flips parity of two vertices, so minimal number of edges added = k/2, each edge adds 2 to excess sum? Wait, each added edge increases e(v) by 1 for two vertices, so total excess sum increases by 2. So to have e(v) odd for all vertices, we need each e(v) to be at least 1. Minimal total excess = k (if each exactly 1). That is achievable by a perfect matching of k/2 edges, each giving +1 to two vertices. So sum excess = k. Then 2L - k(k-1) = k => 2L = k(k-1) + k = k^2 => L = k^2/2, n = L+1 = k^2/2 +1? Wait, L = total edges traversed. If sum excess = k, then 2L = k(k-1) + k = k^2 => L = k^2/2. Then n = L+1 = k^2/2 +1. But earlier we derived minimal n for even k as k^2/2 (open) or k^2/2 +1 (closed). Let's recalc: For even k, we considered closed Eulerian circuit after adding k/2 edges, total edges = E + k/2 = k(k-1)/2 + k/2 = (k^2 - k + k)/2 = k^2/2. Then n = edges + 1 = k^2/2 + 1. That's the closed case. But we previously thought minimal n was k^2/2 for open? Let's double-check.
Wait, I'm mixing up. Let's be systematic:
Define:
E = k(k-1)/2.
We want minimal n (number of vertices) such that there exists a walk (sequence) of length n covering all edges of K_k.
We have two types: closed (start=end) or open (start≠end). The walk's edge count L = n-1.
We need L >= E, and parity condition.
Let's derive minimal L.
Case k odd:
All degrees even -> Eulerian circuit exists: L = E, closed. So n = E+1.
Could we have open with L = E? That would require two odd-degree vertices, but with L=E and each edge traversed exactly once, degrees = original = even, so all even, cannot have open (requires exactly 2 odd). So open not possible with L=E. To have open, we need at least L = E+1 (add one edge) to get two odd vertices. So minimal L = E, n = E+1.
Case k even:
All degrees odd.
For closed: need all d(v) even. To achieve this, we need to add extra edges to make degrees even. Minimal extra edges = k/2 (since we need to flip parity of all k vertices). Each extra edge adds 1 to L? Actually each extra edge is an additional traversal of an edge. So total L = E + extra = E + k/2. Then all d(v) even -> closed Eulerian circuit exists. So n = L+1 = E + k/2 + 1.
For open: need exactly two vertices odd. Since original all odd, we need to flip parity of k-2 vertices to even (so they become even), leaving two odd. To flip k-2 vertices, we need (k-2)/2 extra edges. So extra = (k-2)/2 = k/2 - 1. Then L = E + k/2 - 1. Then we have exactly two odd vertices -> open Eulerian trail exists. Then n = L+1 = E + k/2.
Thus minimal n is min(closed_n, open_n). For even k, closed_n = E + k/2 + 1, open_n = E + k/2. So open_n is smaller by 1. So minimal n = E + k/2.
Thus for even k, minimal n = E + k/2 = k(k-1)/2 + k/2 = (k^2 - k + k)/2 = k^2/2. So n_min = k^2/2.
For odd k, minimal n = E + 1 = k(k-1)/2 + 1 = (k^2 - k + 2)/2.
Thus formulas stand.
Now earlier I mistakenly wrote for even k: n_min = k^2/2. That is correct. In the earlier derivation I said n_min = E + k/2 = k^2/2. Good.
Now, confirm for k=2: 2^2/2 = 2, correct. For k=4: 16/2=8, correct. For k=6: 36/2=18, correct.
Now for odd: k=3: (9-3+2)/2=8/2=4, correct. k=5: (25-5+2)/2=22/2=11. k=1: (1-1+2)/2=2/2=1, correct.
So we have correct formulas.
Now, we need to handle the case when n is huge, but k_max could be maybe 2000? For n=2,000,000, even k up to sqrt(2n)= sqrt(4e6)=2000 gives k^2/2=2,000,000 exactly if k=2000. For k=2001 (odd), (2001^2 -2001+2)/2 = (4,004,001 -2001+2)/2 = (4,002,002)/2=2,001,001 > 2e6. So max feasible k is 2000 (even) if n=2,000,000 exactly. If n is slightly less than 2,000,000, maybe k_max is 1999 (odd) with n_min= (1999^2 -1999+2)/2. Compute 1999^2 = 3,996,001? Actually 2000^2=4,000,000, so 1999^2 = (2000-1)^2 = 4,000,000 -4,000 +1 = 3,996,001. Then n_min = (3,996,001 -1999 +2)/2 = (3,994,004)/2 = 1,997,002. So that's <2e6. So k=1999 feasible. So k_max could be up to 2000. So loop up to 2000 is fine.
Now, I'll implement.
But wait: There is a subtlety: The array must consist of exactly n integers. If n > f(k), we can pad. However, does padding affect the fact that all numbers in S appear at least once? Yes, we keep them. So fine.
Now, check if any other constraints: The coupons allow to use as many numbers qi as you want. So Dima can use each qi arbitrarily many times. So repetitions fine.
Now, ensure that we haven't misinterpreted the payment: "takes wi rubles from Sereja for each qi, which occurs in the array a." Could it be per occurrence? But we already argued against that from sample. Let's double-check sample 1: if per occurrence, maximum payment? Dima could construct array [1,1,1,1,1]? But then only 1 occurs, payment = 2 (since w1=2). Or [2,2,2,2,2] payment = 3. Or mix: maybe [1,2,1,2,2] would give payment = 22 + 33 = 4+9=13, which is >5. So the maximum would be 13, not 5. So it's not per occurrence. So definitely per distinct.
Thus solution is correct.
Now, I'm thinking about if there is any possibility of using a number multiple times to reduce required length? Not really; the minimal length is determined solely by covering all edges.
Thus final answer.
Now, write code.
But caution: The input size: n up to 2e6, m up to 1e5, so we need fast IO. Use scanf/printf or cin with sync. We'll use scanf for safety. But need to output long long, use %I64d or cout. The problem says: "do not use %lld specifier to read or write 64-bit integers in C++. It is preferred to use cin, cout streams or the %I64d specifier." So we can use cin/cout with ios::sync_with_stdio(false); cin.tie(0);.
Now, implement:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
int n, m;
cin >> n >> m;
vector<int> w(m);
for (int i = 0; i < m; ++i) {
int q, ww;
cin >> q >> ww;
w[i] = ww;
}
sort(w.begin(), w.end(), greater<int>());
long long ans = 0;
long long sum = 0;
for (int k = 1; k <= m; ++k) {
sum += w[k-1];
long long need;
if (k % 2 == 0) {
need = 1LL * k * k / 2;
} else {
need = (1LL * k * k - k + 2) / 2;
}
if (need <= n) {
ans = sum;
} else {
break;
}
}
cout << ans << "\n";
return 0;
}
But wait: For k=1, need computed as (1*1 -1 +2)/2 =1, correct.
n=2,m=1,w=[5] => k=1 need=1 <=2 ans=5; output 5. But could we do better? Only one coupon, so 5.
Now, n=2,m=2,w=[100,1] sorted desc=[100,1], k=1 sum=100 need=1 ans=100; k=2 sum=101 need=2<=2 ans=101; output 101. Is it feasible? Use both numbers, need n>=2, we have n=2, can we construct beautiful array with both numbers? Yes: [100,1] or [1,100] works. So payment =100+1=101. Good.
Now, n=3,m=3,w=[100,100,100] => k=1 sum=100 need=1; k=2 sum=200 need=2; k=3 sum=300 need=4? For k=3 need=4 >3, so break. ans=200. Could we actually do with n=3 and three numbers? Minimal required n=4, so not possible. So max sum is 200. Could we get sum 300 by using only two numbers? No. So answer 200.
Now, check n=4,m=3,w as above: k=3 need=4<=4 ans=300. So good.
Now, n=8,m=4,w all high: need=8 for k=4, so sum of all 4. Good.
Now, n=7,m=4: need=8>7, so only up to k=3, sum of top3. That's consistent.
Thus solution seems correct.
Now, think about if there is any scenario where we can have k numbers but not necessarily all pairs covered because we might use a number only once and the adjacency condition might be satisfied in a non-complete way? Wait, the condition says: for each pair x,y (x≠y) that occur, there must exist an adjacent occurrence of x and y (in either order). That means every unordered pair of distinct numbers present must appear as adjacent at some point. So it's exactly covering all edges. So it's complete.
Now, is there any possibility to satisfy the condition with a set S of size k but with a sequence length less than f(k) by having some pairs covered by the same adjacency? No, each adjacency is one unordered pair. So we need at least number of pairs edges. Additionally, parity imposes extra edges for even k. So f(k) is indeed minimal.
Now, I'll produce final answer.
But before final, I recall that there is a known problem: "Beautiful Array" from Codeforces? Possibly similar. Indeed I've seen a problem about beautiful array and coupons. It might be from Codeforces Round #... I recall a solution where you sort wi and compute maximum sum for which k(k-1)/2 + [k even? k/2 : 1] <= n? Something like that. So likely correct.
Let's check if any further nuance: The array must be built by Dima, who wants to maximize payment. But we are asked to find maximum amount Sereja can pay, i.e., the maximum Dima can force. So we are to compute that maximum. So our approach gives that.
Now, what about the case where some wi are negative? Not allowed.
Now, consider the scenario where m is large but k_max is small; we sort all wi but we only need top k_max. Could we avoid sorting all m? We could use nth_element or partial sort, but sorting 100k is fine.
Now, time complexity: O(m log m) sorting, fine.
Now, finalize.
But wait: The problem constraints: n up to 2*10^6, m up to 10^5. But note that qi and wi up to 10^5. So sorting 10^5 ints is fine.
Now, final answer.
But one more check: Are we absolutely sure that for even k, minimal n is k^2/2? Let's test with k=8: E=28, k/2=4, minimal n = E + k/2 = 28+4=32. k^2/2=64/2=32. So n_min=32. Could we find a sequence of length 32 covering all 28 edges? That would have 31 adjacencies. Since we need 28 edges covered, we have 3 extra adjacencies. Are we sure it's possible? We can construct an Eulerian trail after adding k/2 - 1 = 3 extra edges (since open). Total edges = 28+3=31, n=32. So yes. Is there a sequence of length 31? That would be 30 edges, which would be 28+2 extra, but parity might not work. So 32 is minimal.
Now, check k=8, n=31: edges=30. Need to cover 28 edges, so extra =2. That would require sum excess = 2*2? Actually extra edges 2 gives excess sum =4? Wait, each added edge increases excess sum by 2. So with 2 extra edges, total excess sum =4. Then sum e(v) =4. But we need parity: for even k, original all odd. To have open walk (2 odd vertices), we need e(v) even for the two odd? Actually we need d(v) odd for exactly two vertices. Since d(v)= odd + e(v). So we need e(v) even for exactly two vertices and odd for the rest? Let's compute: For open, we need exactly two vertices where d(v) odd. Since original odd, d(v) odd when e(v) even (since odd+even=odd). So we need exactly two vertices with e(v) even, and the other k-2 vertices with e(v) odd. Now, with total excess sum =4, and we need e(v) odd for 6 vertices (since k=8, need 6 odd e(v)), each odd e(v) must be at least 1. So minimal sum for those 6 vertices is 6 (if each exactly 1). That's already >4. So impossible. So n=31 not feasible. So 32 is minimal. Good.
Thus correct.
Now, ensure that our calculation of need for odd k also correct: k=5, need=11. Could we do with n=10? edges=9, need cover 10 edges, impossible. n=11 edges=10, which is exactly E, but for odd k we can have closed Eulerian circuit with E edges. That yields n=11. So feasible.
Now, all good.
Thus final code.
But wait: The problem statement says "Sereja wants to build a beautiful array a, consisting of n integers." But then "Dima builds some beautiful array a of n elements." So it's Dima building it. But we computed maximum payment that Dima can force, which is the answer.
Now, maybe there is another interpretation: "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." So Sereja is worried about the maximum he might have to pay, i.e., the worst-case scenario given Dima can choose any beautiful array using the coupons. So we compute maximum possible sum, as we did.
Now, sometimes there is a twist: Perhaps Sereja has to pay for each occurrence of qi, not per distinct. But we already reasoned against that with sample. So it's per distinct.
Now, confirm with sample 1: If per distinct, answer 5. If per occurrence, Dima could do array [1,2,1,2,2] and charge 2+3 per occurrence? That would be 5*? Actually each occurrence: 1 appears twice => 22=4, 2 appears three times =>33=9, total=13. But could Dima do even better? Possibly [2,2,2,2,2] gives 5*3=15. So maximum per occurrence would be max wi * n? Since we can fill array with the number having highest wi. So with w2=3, n=5 => 15. But output is 5, so not per occurrence.
Thus correct.
Now, final answer.
But wait: There is a nuance: The coupons allow you to use as many numbers qi as you want, but perhaps using a coupon costs wi rubles per coupon? Actually the wording: "Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a." This might imply that to use number qi, you need to "pay" wi to purchase the coupon? But then it says "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." So Dima already has the coupons, and he charges Sereja for each qi that appears. So it's per distinct.
All good.
Now, write final solution.
But we need to ensure we use 64-bit for sum. We'll use long long.
Now, I'll add a quick check: if m is zero? But m>=1 per constraints (1 ≤ m). So fine.
Now, final code.
But I just thought: Could there be a scenario where the set S includes numbers, but we might not need to cover all pairs if we arrange the array such that some pair appears as adjacency through a third number? No, condition explicitly says for each pair x,y, there must be a position where x and y are adjacent. So they must be directly adjacent. So no indirect.
Now, done.
I'll produce final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m;
cin >> n >> m;
vector<int> w(m);
for (int i = 0; i < m; ++i) {
int q, val;
cin >> q >> val;
w[i] = val;
}
// take the largest wi first
sort(w.begin(), w.end(), greater<int>());
long long ans = 0, cur_sum = 0;
for (int k = 1; k <= m; ++k) {
cur_sum += w[k - 1];
// minimal n needed for a set of size k
long long need;
if (k % 2 == 0) {
need = 1LL * k * k / 2; // even k
} else {
need = (1LL * k * k - k + 2) / 2; // odd k (works for k=1 as well)
}
if (need <= n) {
ans = cur_sum; // we can use these k numbers
} else {
break; // larger k will need even larger n
}
}
cout << ans << "\n";
return 0;