Hi, this is part of a recursion problem and after very long, I still can't figure out why the output to the 2nd part of the qn is too large. Can anyone help? Thanks.
The qn is as follows: There are N warriors (N <= 20) each with an estimated strength. Some pair of warriors have conflict with one another and cannot be in the same army. Choose the strongest army from these warriors and output the max strength of the army (strength) and the no of ways to form an army of this strength (ways).
I created an array warrior[21] where warrior[i] store the strength of the ith warrior and fight[21][21] is a dimensional boolean array such that fight[x][y] return true if the xth and yth warrior cannot be in the same army. In the main program, I made a call to maxstrength(warrior,1,n,army,fight).
I declared strengths and ways as global variables initialised to 0.
army[i] is true if I decided to add warrior[i] to my army.
size is the actual no of warriors (n) in the input. it is less than 21. so I only use part of the array.
My recursive function is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
void maxstrength(int arr[21],int i ,int size, bool army[21],bool fight[21][21]){
if (i > size){
int val = 0;
for (int j=0;j<21;i++){
if (army[j]){
val += arr[j];}
}
if (val > strength){strength = val; ways =1;}
else if (val == strength){ ways++; }
return;
}
else {
//dont choose
maxstrength(arr,i+1,size,army,fight);
//can choose?
bool can_choose = true;
for (int j=1;j<i;j++){
if (army[j] && fight[j][i]){
can_choose = false;
break;
}
}
if (can_choose)
army[i] = true;
maxstrength(arr,i+1,size,army,fight);
army[i] = false;
}
}
|
e.g.
warrior = [3,3,2,2,1] and the pair (1,2) and (4,5) have a conflict.
hence, the max strength should be 7 (warrior 1,3,4 or 2,3,4)
I obtained the correct strength (7) in the end but i got too many ways (6 instead of 2). What is the error? Does it has to do with global variables or did I pass the wrong parameters?