Ambiguous Permutations Problem

Consider the following question:
http://www.spoj.com/problems/PERMUT2/

The code that I've written is:
 ``123456789101112131415161718192021222324252627282930313233`` ``````#include #include using std::cin; using std::cout; using std::vector; int main() { int num; vector arr1, arr2; while(cin >> num) { arr1.push_back(num); } auto n = arr1.size(); for(int i=0; i!=n; ++i) { arr2[arr1[i]-1] = (i+1); } for(int i=0; i!=n; ++i) { if(arr1[i]!=arr2[i]) { cout << "Not Ambiguous\n"; break; } else continue; cout << "Ambiguous\n"; } return 0; }``````

I don't understand what's wrong with this code. It just keeps crashing after taking inputs properly. Can anyone help me?
`arr2[arr1[i]-1]`
arr2 is empty and doent have any elements. You are accessing out of bounds (or trying to dereference a null pointer depending on realization).
If you not sure if you can accidently try to access out of bounds, use at() member functions, at leas it wil give you a hint what the problem is: `arr2.at(arr1[i]-1)`
Wouldn't the same problem persist even after I use the `at()` function? How can I correct this issue?
It will, but you will see what the problem is next time. In your case you should rethink your program algorithm.

Actually you can do `arr2.reserve(arr1.size())` but your code still isn't very good.
Last edited on
your code still isn't very good.

Any Suggestions for Improvement?
Topic archived. No new replies allowed.