CCCPaste

Google Code Jam 2020 Q1.2 [Nesting Depth]

#include 
using namespace std;

#define INF INT_MAX
#define LINF LLONG_MAX
#define forin(data) for(auto &i : data)
#define debug(x) cerr << #x << " = " << x << endl;

using ll = long long;
using pi = pair;
using vi = vector;
using vii = vector;
using vl = vector;

void init(){
    #ifdef LOCAL
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
        freopen("log.txt", "w", stderr);
    #else
        cin.tie(0); cout.tie(0);
        ios_base::sync_with_stdio(0);
    #endif
}

int toInt(char i){
    return (i - '0');
}

void append(string &str, int n, char c){
    for(int i = 0; i < n; i++){
        str += c;
    }
    cout << str << endl;
}

int main(){
	init()
    int tc;
    cin >> tc;
    for(int i = 1; i <= tc; i++){
        string str;
        cin >> str;
        string ans = "";
        if(str.size() == 1){
            append(ans, toInt(str[0]), '(');
            ans += str[0];
            append(ans, toInt(str[0]), ')');
        }else{
            int left, right, brac;
            left = right = brac = 0;
            for(int j = 0; j < str.size(); j++){
                if(j == 0){
                    left = toInt(str[j]);
                    right = toInt(str[j]) - toInt(str[j + 1]);
                }else if(j == str.size() - 1){
                    left = toInt(str[j]) - toInt(str[j - 1]);
                    if(left > 0){
                        append(ans, left, '(');
                        brac += left;
                    }
                    right = brac;
                    ans += str[j];
                    append(ans, right, ')');
                    break;
                }else{
                    left = toInt(str[j]) - toInt(str[j - 1]);
                    right = toInt(str[j]) - toInt(str[j + 1]);
                }
                if(left > 0){
                    append(ans, left, '(');
                    brac += left;
                }
                ans += str[j];
                if(right >= 0){
                    append(ans, right, ')');
                    brac -= right;
                }
            }
        }
        cout << "Case #" << i << ": " << ans << endl;
    }
    return 0;
}