PostMunwai's blog

By PostMunwai, history, 8 years ago, translation, In English

Hello everybody! I'm new to programming, I am solving problem 160А, but the C ++ compiler surprised me very much.

According to the idea ** cout ** should not affect the logic (it's just ** cout **), but somehow effects.

With cout

Withoud cout

Here is my (awful) code:

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

int main() {
    int n;
    int result = 0;
    int point = 0;
    int sum = 0;
    
    cin >> n;
    int a[n];
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    
    // sort 
    int temp;
    int count = (sizeof(a)/sizeof(*a));
    for(int i = 0; i < count; i++) {
        for(int j = 0; j < count; j++) {
            if(a[j] > a[j+1]) {
                temp = a[j];
		a[j] = a[j+1];
		a[j+1] = temp;
            }
        }
    }
    
    
    //reverse
    int reverse_temp;
    for (int i = 0; i < count/2; ++i) {
        reverse_temp = a[count-i-1];
        a[count-i-1] = a[i];
        a[i] = reverse_temp;
    }
    
    
    

    for(int i = 0; i < count; i++) {
        point = point + a[i];
        // cout << "point: " << point << endl;
        result = result + 1;
        // cout << "result :" << result << endl;
        
        for(int j = result; j < count; j++) {
            sum = sum + a[j];
            // cout << "sum: " << sum << endl;
        }
        
        if(point > sum) {
            cout << "answer: " << result << endl;
            break;
        } else {
            sum = 0;
        }
        
    }
    
    return 0;
}
  • Vote: I like it
  • -16
  • Vote: I do not like it

| Write comment?
»
8 years ago, # |
  Vote: I like it +3 Vote: I do not like it

Change count to count-1 on line 20 and it should be fixed. This usually happens when you try to access element that is not part of the array, causing UB bug.

  • »
    »
    8 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks, it worked. I try not to allow such mistakes again)

    • »
      »
      »
      8 years ago, # ^ |
      Rev. 3   Vote: I like it 0 Vote: I do not like it

      Don't worry about it, I still make mistakes like this sometimes, I just get better at detecting such problems.

      btw, u can sort array using sort(a, a+n) in nlogn. or even sort in decreasing order with sort(a, a+n, greater<int>());

      and if you use vector, u can sort with sort(a.begin(), a.end()) and in decreasing order with sort(a.begin(), a.end(), greater<int>());

      and u can even reverse the vector with reverse(a.begin(), a.end())