tinycodinglm / cp2 /cp-0046.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
3.35 kB
cp-practice-sim trace
System You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space com...

You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space complexity.

User 2026-11-08T19:20:03.537Z

Jackpot Number

Topic: Sorting and greedy | Difficulty: medium

Problem

You are given n non-negative integers written in decimal without leading zeros (the number zero is written "0"). Concatenate all of them, each exactly once, in an order of your choice, to form one long digit string. Print the numerically largest result. If the largest result consists only of zeros, print a single "0".

Input

The first line contains n. The second line contains the n numbers as tokens.

Output

Print the largest concatenation as a digit string.

Constraints

  • 1 <= n <= 10^5
  • each number is between 0 and 10^9

Examples

Example 1

Input:

markdown
5
3 30 34 5 9

Output:

markdown
9534330

Example 2

Input:

markdown
3
0 0 0

Output:

markdown
0

Note: Zeros collapse to a single 0.

Solve this in JavaScript (Node.js), Ruby, C#, one complete program per language. Include a concise rationale (approach, correctness idea, time/space complexity).

Assistant 2026-11-08T19:20:05.511Z

Approach. Sort the tokens with the comparator "a before b iff a+b > b+a" as strings, then join them. If the first token is "0", the answer is "0".

Correctness. The relation a+b >= b+a is a total preorder (it compares a/(10^len(a)-1) against b/(10^len(b)-1)), and swapping an adjacent inverted pair strictly increases the concatenation, so the sorted order is optimal.

Complexity. Time: O(n log n * L). Space: O(n * L).

JavaScript (Node.js)

javascript
const d = require('fs').readFileSync(0, 'utf8').split(/\s+/).filter(x => x);
const n = parseInt(d[0]);
const a = d.slice(1, n + 1);
a.sort((x, y) => {
  const p = x + y, q = y + x;
  return p < q ? 1 : p > q ? -1 : 0;
});
console.log(a[0] === '0' ? '0' : a.join(''));

Ruby

ruby
n = gets.to_i
a = gets.split.first(n)
a.sort! { |x, y| (y + x) <=> (x + y) }
puts(a[0] == '0' ? '0' : a.join)

C#

csharp
using System;
using System.Text;

class Program {
    static void Main() {
        int n = int.Parse(Console.ReadLine().Trim());
        string[] a = Console.ReadLine().Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
        Array.Sort(a, (x, y) => string.CompareOrdinal(y + x, x + y));
        if (a[0] == "0") { Console.WriteLine("0"); return; }
        Console.WriteLine(string.Concat(a));
    }
}