Temporarily, Codeforces is operating in a limited mode due to technical reasons (historical data is unavailable). This will be fixed in the next few hours. ×
Rating changes for last rounds are temporarily rolled back. They will be returned soon. ×

syedaaliyanx's blog

By syedaaliyanx, history, 4 hours ago, In English

Problem: https://atcoder.jp/contests/abc220/tasks/abc220_c

A good problem for beginners who want to improve their logic building and learn basic optimization.

The Idea: A straightforward approach is to keep adding elements until the sum exceeds X. But when X is very large, this can be too slow.

Instead, calculate the sum of one complete array. Use integer division to skip as many complete repetitions as possible, then process the remaining elements one by one.

C++ Solution

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


int main() 
{ 
    long long n; 
    cin >> n; 

    vector<long long> a(n); 
    long long total = 0; 

    for (int i = 0; i < n; i++) 
    { 
        cin >> a[i]; 
        total += a[i]; 
    } 

    long long x; 
    cin >> x; 

    long long cycles = x / total; 
    long long sum = cycles * total; 
    long long count = cycles * n; 

    for (int i = 0; i < n; i++) 
    { 
        sum += a[i]; 
        count++; 

        if (sum > x) 
        { 
            cout << count << '\n'; 
            return 0; 
        } 
    } 

    return 0;
}

What Can You Learn? - Why a brute-force approach can be too slow. - How to use maths to skip repeated operations. - How to turn a straightforward solution into an efficient one.

NOTE:

I'm a beginner myself, and I really enjoyed solving this problem, so I thought I'd share it. If you spot any mistakes, feel free to point them out!

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it