Could anyone help me? I'm stuck on January 2020 USACO Bronze Problem 2

Somehow, 8/10 tests are good and seem to work, while for other 2, the answers are incorrect. Could anyone help and tell my what is wrong with my code? It’s strange because I tried all possible examples within the boundary of the problem and I still cannot solve the remaining two tests for some reason. Below is the code:
------------------------------------------------------------------------------------------------------------------------------------

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

#define ll long long  
#define pb push_back
#define ALL(v) v.begin(), v.end()
#define RALL(v) v.rbegin(), v.rend()

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    ifstream fin ("photo.in");
    ofstream fout ("photo.out");
    
    vector<int> a;
    int n, val, x;
    fin >> n;

    for(int i = 0; i < n-1; i++){
        fin >> val;
        a.pb(val);
    }
    vector<int> ans;
    for(int i = 1; i < a[0]; i++){
        x = i;
        for(int j = 0; j < (n-1); j++){
            if((a[j] - x)  == x)break;
            if((a[j] - x) > n)break;
            ans.pb(x);
            x = a[j] - x;
        }
        if(ans.size() == (n-1)){
            ans.pb(x);
            break;
        }else{
            ans.clear();
        }
    }
    if(ans.size() == 0){
        fout << 0 << '\n';
        return 0;
    }
    for(int i = 0; i < n; i++){
        if(i == n-1){
            fout << ans[i];
            break;
        }
        fout << ans[i] << " ";
    }
    fout << '\n';
    return 0;
}

Are you remembering to check if your ans vector is forming a permutation? I think there are cases where your vector would form an array of size n with elements from 1 to n but there could be duplicates? You should add in something to make sure that all the values from 1 to n appear exactly once.

1 Like

Thanks! I will implement that to the code and check if the ans vector is a permutation

It’s all good thanks! I just solved it