Output File Empty in USACO

Problem

2020 January Bronze: 2. Photoshoot

Question

The code executes fine in a debugger, and it properly outputs into the photo.out about half the time when I run it. However, when I submit the code to USACO, it says the photo.out file is empty. Am I handling input/output incorrectly?

What I’ve Tried

Sometimes, adding additional unrelated cout statements makes it print out the output at the end. I have also tried it using stdin and stdout without in/out files, but that produces the same effect.

My Work

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

int main() {
  freopen("photo.in", "r", stdin);
  freopen("photo.out", "w", stdout);
  ios::sync_with_stdio(0);
  cin.tie(0);

  int n;
  cin >> n;
  int nums[n - 1];
  for (int i { 0 }; i < n - 1; i++) {
    cin >> nums[i];
  }
  for (int i { 1 }; i < nums[0]; i++) {
    if (i == nums[0] - i) continue;
    bool valid { true };
    int sequence[n];
    sequence[0] = i;
    int used[n] {};
    used[i - 1] = 1;
    for (int j { 1 }; j < n; j++) {
      int val { nums[j - 1] - sequence[j - 1] };
      if (val >= nums[j] || used[val - 1]) {
        valid = false;
        break;
      }
      sequence[j] = val;
      used[val - 1] = 1;
    }
    if (valid) {
      for (int j { 0 }; j < n; j++) {
        cout << sequence[j];
        if (j != n - 1) cout << ' ';
      }
      break;
    }
  }
}
1 Like

If I compile with -fsanitize=undefined and run your code, I see that the code is going out of bounds on the sample case. See this module for more info: Debugging C++

Compiling and Running:

g++ -std=c++17 oops.cpp -fsanitize=undefined -o oops && ./oops < oops.in

Error:

oops.cpp:20:24: runtime error: index 4 out of bounds for type 'int[n - 1]'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior oops.cpp:20:24 in 

Code:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    int nums[n - 1];
    for (int i{0}; i < n - 1; i++) { cin >> nums[i]; }
    for (int i{1}; i < nums[0]; i++) {
        if (i == nums[0] - i) continue;
        bool valid{true};
        int sequence[n];
        sequence[0] = i;
        // int used[n]{}; // this doesn't compile with clang ...
        vector<int> used(n);
        used[i - 1] = 1;
        for (int j{1}; j < n; j++) {
            int val{nums[j - 1] - sequence[j - 1]};
            if (val >= nums[j] || used[val - 1]) {
                valid = false;
                break;
            }
            sequence[j] = val;
            used[val - 1] = 1;
        }
        if (valid) {
            for (int j{0}; j < n; j++) {
                cout << sequence[j];
                if (j != n - 1) cout << ' ';
            }
            break;
        }
    }
}
1 Like

Thank you, that helped me identify the issue! When the code was checking val >= nums[j], j could be n - 1, resulting in the index going out of bounds.