Codeforces 1788B: Sum of Two Numbers

Problem
Given , find with and , where is digit sum. Up to tests.
Why brute force fails
Looping from to is per test. With and , that’s ops. Need to think in digits, not magnitude.
Key fact
Split digit by digit: pick with . No carries, so
(Each carry subtracts from the digit sum total. No carries, no loss.)
The total is fixed. So the question becomes: how do we split each digit so and end up balanced?
The split
For digit , the best you can do alone is vs . Even digits split evenly. Odd digits leave a imbalance.
If every odd digit’s bigger half goes to , the imbalance can hit . Alternate instead: flip which side gets the bigger half each time you see an odd digit. Imbalance stays in .
Trace,
| digit | sign | ||
|---|---|---|---|
| 1 | 1 | 0 | flip |
| 2 | 11 | 1 | |
| 0 | 110 | 10 | |
| 6 | 1103 | 103 |
. , .
Code
#include <bits/stdc++.h>
using namespace std;
// accepted in 46ms
int main() {
int t; scanf("%d", &t);
while (t--) {
long long n; scanf("%lld", &n);
string s = to_string(n);
long long x = 0, y = 0;
int sign = 1;
for (char c : s) {
int d = c - '0', big = (d+1)/2, small = d/2;
if (d % 2 == 0) { x = x*10+big; y = y*10+small; }
else if (sign == 1) { x = x*10+big; y = y*10+small; sign = -1; }
else { x = x*10+small; y = y*10+big; sign = 1; }
}
printf("%lld %lld\n", x, y);
}
}
Complexity
per test, total. About ops worst case.