---
id: 2625
lang: en
translation_of: index.md
source_sha256: e8c0918723ae30dbd93015b2cd64506f94cbd2425887d8b5c37def1d48a92c31
title: "[Codeforces 662A] Gambling Nim — Solution"
description: "Let S be the XOR of all a_i, throw c_i = a_i xor b_i into a linear basis, and check whether S can be formed to get the probability of winning."
tags: ["OI","Bitwise Operations","Linear Basis"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "线性基最少数来拼出一个和 S 一样的数使得局面必输 is elliptical in the original; rendered literally as “the linear basis, with the fewest numbers, pieces together a number equal to S, which makes the position a guaranteed loss”."
  - "赢得概率 is read as 赢的概率 (“the probability of winning”), a common typo."
---

## Main Idea

Consider letting $S = \oplus_{i = 1}^n a_i$, then throw $c_i = a_i \oplus b_i$ into a linear basis. We can see that the linear basis, with the fewest numbers, pieces together a number equal to $S$, which makes the position a guaranteed loss. Then the probability of winning is $1 - (\frac12)^{siz}$.

Of course, if it can't be pieced together, then it's a sure win.

<!--more-->

## Code

```cpp
// CF662A.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 5e5 + 200;

typedef long long ll;

int n, bcnt;
ll ai[MAX_N], bi[MAX_N], ci[MAX_N], S, base[200];

bool insert(ll x)
{
	for (int i = 1; i <= bcnt + 1; i++)
		x = min(x, x ^ base[i]);
	if (x > 0)
		base[++bcnt] = x;
	return x > 0;
}

int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%lld%lld", &ai[i], &bi[i]), S ^= ai[i], insert(ai[i] ^ bi[i]);
	if (insert(S))
		puts("1/1");
	else
		printf("%lld/%lld\n", (1LL << bcnt) - 1, 1LL << bcnt);
	return 0;
}
```
