Official

C - String Too Long Editorial by en_translator


The problem can be solved by first accepting all the input, printing Too Long if the sum of \(l_i\) (i.e. the length of \(S\)) is greater than \(100\), and printing \(c_i\) \(l_i\) times for each \(i\) if it is \(100\) or less.

Beware of overflows. For example, if you try to use long long to find the sum of \(l_i\), your answer will be judged Wrong Answer.

long long sum = 0;
for (int i = 0; i < N; i++) {
  char c;
  long long l;
  cin >> c >> l;
  sum += l;
}
if (sum > 100) {
  cout << "Too Long";
} else {
  // Print S
}
Hack case For example, the program fails when the sum is $2^{64}+100$.
19
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 1000000000000000000
b 1000000000000000000
a 446744073709551716  


To avoid this, in the loop to find sum, we can immediately terminate the program once sum exceeds \(100\).

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
  int N;
  vector<pair<char, ll>> P;
  cin >> N;
  ll sum = 0;
  for (int i = 0; i < N; i++) {
    char c;
    ll L;
    cin >> c >> L;
    sum += L;
    if (sum > 100) {
      cout << "Too Long" << endl;
      return 0;
    }
    P.push_back({c, L});
  }
  for (auto [c, l] : P) {
    while (l--) cout << c;
  }
  cout << endl;
}

If you are using languages like Python, where overflows do not become an issue, you can naively write the code.

Sample code(Python)

N = int(input())
P = []
for i in range(N):
    c, l = input().split()
    P.append([c, int(l)])
if sum(map(lambda x: x[1], P)) > 100:
    print("Too Long")
else:
    S = ""
    for c, l in P:
        S += c * l
    print(S)

posted:
last update: