0%

Codeforces gym 101611D. Decoding of Varints 题解

题解

阅读理解题,讲的是把一个大数转换成一种类似 \(2^7\) 进制的编码规则,直接看题目中给的样例可以很快理解: \[ \begin{aligned} 260 =(b_0-128)\cdot 2^0+b_1\cdot 2^1 \\ =(132-128)\cdot 2^0+2\cdot 2^1 \end{aligned} \]

即除了最高的一位 \(b_i< 128\) ,其他位均为 \(\geq 128\),我们就按照这个规则对给出的 \(b_i\) 进行组合即可。

题目最后还有一个把无符号转换成有符号的规则 zig-zag ,分奇偶输出即可(注意 ans+1 可能会爆掉 unsigned long long ,直接转换为 __int128 防止溢出)。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// https://codeforces.com/gym/101611/problem/D
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

template <typename _Tp>
void read(_Tp &a, char c = 0, int f = 1) {
for(c = getchar(); !isdigit(c); c = getchar()) if(c == '-') f = -1;
for(a = 0; isdigit(c); a = a * 10 + c - '0', c = getchar()); a *= f;
}

template <typename _Tp>
void write(_Tp a) {
if(a < 0) putchar('-'), a = -a;
if(a > 9) write(a / 10); putchar(a % 10 + '0');
}

const int N = 1e4 + 5;
ull n, a[N];

int main() {
// freopen("0731_2.in", "r", stdin);
read(n);
for(int i = 1; i <= n; i++) {
read(a[i]);
}
int p = 1;
while(p <= n) {
ull base = 1 << 7; // base unit of 7 bits
ull tmp = 1;
ull ans = 0;
int _p = p;
for(; _p <= n; _p++) {
// printf("_p = %d\n", _p);
if(a[_p] < 128) {
ans += a[_p] * tmp;
p = _p;
break;
}
ans += (a[_p] - 128) * tmp;
tmp *= base;
}
// write(ans), putchar('\n');
if(ans & 1) {
putchar('-'), write((__int128(ans) + 1) / 2), putchar('\n');
} else {
write(ans / 2), putchar('\n');
}
p++;
}
return 0;
}