I'm trying to solve 136A-Presents in Codeforces. My program crashes when trying to enter the second input. This is my first time to code with maps. What's wrong with my code?
#include <map>
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
unsigned n; // number of friends
scanf("%u", n);
unsigned f[n]; // array of numbered friends
for(int c = 0; c < n; c++)
scanf("%u", f[c]); // getting input that tells you, for each friend to whom he gave a gift.
map<unsigned, unsigned> friends; // a map of friends, mapped by their digits and given numbers.
for(int i = 0; i < n; i++)
friends[f[i]] = i+1;
// ^ ^
// input indexes from 1 to n
/* Since keys are already sorted in the map, there is no need to re-sort them again. */
for(int j = 0; j < n; j++){
printf("%u", friends[j]); // printing values of keys.
if(j != n-1)
printf(" ");
}
return 0;
}
I think using the map that way is OK, but if I read your comments right, you might have the value and key reversed. Remember, that if the keys aren't unique then the way you're doing will just change the value for any key you try to add more than once, not create another key. However,
scanf
needs a pointer to an object whose type corresponds to the format string, and you aren't even declaring what type of arrayf
is. If you have some non standard compiler that recognizes, or if you're defining, unsigned as unsigned int, then try: