EN VI

C++ - Answer is wrong when i include sort() function (Rudolf and the ticket from codeforces)?

2024-03-13 21:30:06
C++ - Answer is wrong when i include sort() function (Rudolf and the ticket from codeforces)

so i was wondering why my code somehow gives the correct output only when i remove the 2 sort functions as the value themselves don't change?

The question

Also, I'm unable to post on code forces yet as I'm a beginner so i thought i could get help here. Thanks so much in advance!

My code:

#include <bits/stdc++.h>
using namespace std;
 
int main(){
    int t;
    cin >> t;
    
    while(t--){
        int n, m, k, count = 0;
        cin >> n >> m >> k;
        int A[1000], B[1000];
        for (int i = 0; i < n; i++){
            cin >> A[i];
        }
        for(int i = 0; i < m; i++){
            cin >> B[i];
        }
        sort(begin(A), end(A));
        sort(begin(B), end(B));
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(A[i] + B[j] <= k){
                    count++;
                }
                
            }
        }
        cout << count << endl;
    }
}

Can't figure out why it will only work when i remove sort function

Solution:

sort(begin(A), end(A)); sorts the all 1000 elements of the array int A[1000];. This includes uninitialized elements, so the sorting may put garbage values to what is processed and may lead to wrong output.

Removing the sorting eliminates this garbage putting and make the output correct.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login