Reputation: 839
So I wanted to write code which solves this problem: "Collecting Beepers" And I did:
int rec(int current, int beers)
{
if(beers == (1 << (numOfBeers + 1)) - 1) return cost(beerX[0], beerY[0], beerX[current], beerY[current]);
int optimal = 100000;
for(int i = 1; i <= numOfBeers; ++i)
{
if(((1 << i) & beers) == 0)
{
int newBeersSet = (1 << i) | beers;
int c = cost(beerX[current], beerY[current], beerX[i], beerY[i]);
int current = c + rec(i, newBeersSet);
optimal = min(optimal, current);
}
}
return optimal;
}
The strange thing is, that when I replace the part
int c = cost(beerX[current], beerY[current], beerX[i], beerY[i]);
int current = c + rec(i, newBeersSet);
with
int current = cost(beerX[current], beerY[current], beerX[i], beerY[i]) + rec(i, newBeersSet);
the logic is absolutely the same and yet my program crashes on the same (the one given in the problem desciption) input and the online judge gives wrong answer as a result from the program execution while with the original code it gives Accepted. Any ideas what could possibly be wrong?
Upvotes: 2
Views: 84
Reputation: 1774
That is propably because your variable "current" is overriden. Try:
int current2 = cost(beerX[current], beerY[current], beerX[i], beerY[i]) + rec(i, newBeersSet);
optimal = min(optimal, current2);
Upvotes: 2
Reputation: 141618
In this line you are using an uninitialized variable:
int current = cost(beerX[current], // ...
This declares a new variable current
and then, before the variable has had a value assigned, uses it as index to beerX
.
You probably meant:
int new_current = cost(beerX[current], // ...
which uses the existing current
variable which was declared in the parameter list for the rec
function.
Upvotes: 2