CSES - Aalto Competitive Programming 2024 - wk12 Homework - Results
Submission details
Task:Missing Coin Sum
Sender:notado
Submission time:2024-11-25 18:27:54 +0200
Language:C++ (C++20)
Status:READY
Result:0
Feedback
groupverdictscore
#10
Test results
testverdicttime
#10.00 sdetails
#20.00 sdetails
#30.00 sdetails
#40.11 sdetails
#50.12 sdetails
#60.11 sdetails
#70.00 sdetails
#80.05 sdetails
#90.00 sdetails

Code

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

// Custom hash function to prevent unordered_map from worst-case performance
struct custom_hash {
    // Splitmix64 hash function for better distribution
    size_t operator()(const long long& key) const {
        size_t res = key;
        res += 0x9e3779b97f4a7c15;
        res = (res ^ (res >> 30)) * 0xbf58476d1ce4e5b9;
        res = (res ^ (res >> 27)) * 0x94d049bb133111eb;
        res = res ^ (res >> 31);
        return res;
    }
};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    long long n, x;
    cin >> n >> x; // Read the size of the array and the target sum
    
    vector<long long> a(n);
    for(auto &num : a) cin >> num; // Read the array elements
    
    // Initialize an unordered_map with the custom hash
    // The map will store prefix_sum -> frequency
    unordered_map<long long, long long, custom_hash> prefix_counts;
    prefix_counts[0] = 1; // Base case: prefix_sum of 0 occurs once
    
    long long current_sum = 0; // Initialize current prefix sum
    long long answer = 0; // Initialize the answer
    
    // Iterate through the array
    for(int i = 0; i < n; ++i){
        current_sum += a[i]; // Update the current prefix sum
        
        // Check if (current_sum - x) exists in the map
        // If it does, it means there's a subarray ending at index i with sum x
        if(prefix_counts.find(current_sum - x) != prefix_counts.end()){
            answer += prefix_counts[current_sum - x];
        }
        
        // Update the map with the current prefix sum
        prefix_counts[current_sum]++;
    }
    
    cout << answer; // Output the total number of qualifying subarrays
}

Test details

Test 1

Verdict:

input
4
2 1 4 3

correct output
11

user output
0

Test 2

Verdict:

input
4
2 2 2 2

correct output
1

user output
4

Test 3

Verdict:

input
6
1 9 9 1 2 2

correct output
7

user output
1

Test 4

Verdict:

input
200000
38 62 12 96 82 18 48 47 22 3 6...

correct output
10114269

user output
2879

Test 5

Verdict:

input
200000
321076699 332784673 745614086 ...

correct output
1

user output
0

Test 6

Verdict:

input
200000
1 136292223 60613622 935902310...

correct output
5069547

user output
942

Test 7

Verdict:

input
60
1 2 4 8 16 32 64 128 256 512 1...

correct output
31073741824

user output
0

Test 8

Verdict:

input
100000
1 2 4 8 16 32 64 128 256 512 1...

correct output
53672058814464

user output
0

Test 9

Verdict:

input
10
1 1 1 1 1 1 1 1 2 7

correct output
18

user output
7