tinycodinglm / cp2 /cp-0036.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
3.14 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. Reply with code only; no explanation.

You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Reply with code only; no explanation.

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

Palindromic Shelf Segments

Topic: Hashing and counting (maps/sets) | Difficulty: medium

Problem

You are given a sequence of n integers, each between 0 and 19. Count the contiguous non-empty segments whose elements can be rearranged into a palindrome, that is, segments in which at most one value occurs an odd number of times.

Input

The first line contains n. The second line contains n integers.

Output

One integer, the number of such segments.

Constraints

  • 1 <= n <= 2*10^5
  • 0 <= a_i <= 19

Examples

Example 1

Input:

markdown
3
1 1 2

Output:

markdown
5

Note: Three single elements, [1,1] and [1,1,2]; [1,2] fails.

Example 2

Input:

markdown
4
0 1 2 3

Output:

markdown
4

Example 3

Input:

markdown
4
5 5 5 5

Output:

markdown
10

Solve this in JavaScript (Node.js), Ruby, C#, one complete program per language. Code only, no explanation.

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

JavaScript (Node.js)

javascript
const t = require('fs').readFileSync(0, 'utf8').split(/\s+/).filter(x => x).map(Number);
const n = t[0];
const cnt = new Int32Array(1 << 20);
cnt[0] = 1;
let cur = 0, ans = 0;
for (let i = 1; i <= n; i++) {
  cur ^= 1 << t[i];
  ans += cnt[cur];
  for (let b = 0; b < 20; b++) ans += cnt[cur ^ (1 << b)];
  cnt[cur]++;
}
console.log(String(ans));

Ruby

ruby
data = STDIN.read.split.map(&:to_i)
n = data[0]
cnt = Array.new(1 << 20, 0)
cnt[0] = 1
cur = 0
ans = 0
(1..n).each do |i|
  cur ^= 1 << data[i]
  ans += cnt[cur]
  20.times { |b| ans += cnt[cur ^ (1 << b)] }
  cnt[cur] += 1
end
puts ans

C#

csharp
using System;

class Program
{
    static void Main()
    {
        var t = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
        int n = int.Parse(t[0]);
        int[] cnt = new int[1 << 20];
        cnt[0] = 1;
        int cur = 0;
        long ans = 0;
        for (int i = 1; i <= n; i++)
        {
            cur ^= 1 << int.Parse(t[i]);
            ans += cnt[cur];
            for (int b = 0; b < 20; b++) ans += cnt[cur ^ (1 << b)];
            cnt[cur]++;
        }
        Console.WriteLine(ans);
    }
}