So this is the question:
Batman, Superman, and Captain America are searching for a group of thugs hiding in a building on New York's 5th Avenue. In order not to look for the same places, the heroes have agreed to search the buildings as follows:
Batman will start looking for the first building on the left and move one building to the right.
Captain America will start the search from the first building on the right and move one building to the left.
Superman, because he can fly, will apply the binary search algorithm to search the buildings. That is, he will first search the building in the middle of 5th Avenue and move left or right accordingly.
If you are given N integers sorted in ascending order indicating the building numbers and then an integer X denoting the building that the villains have fled, create a program that displays the name of the hero who will be able to first detect the villains, searching for the fewest buildings. If some heroes find the villains at the same time, all their names appear in alphabetical order.
Input Format:
An integer N, followed by N integers sorted in ascending order.
Constraints
0
Output Format:
Show the name of the hero who will be able to locate the villains first, looking for the fewest buildings. If some heroes find the villains at the same time, all their names appear in alphabetical order.
Sample Input 0
9
20 30 40 50 60 100 200 500 1000
500
Sample Output 0
Captain America
End of problem. This is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int batman(int arr[], int x)
{
for (int p = 0; p < n; p++)
{
if (arr[p] == x)
return p;
}
}
int cap(int arr[], int x)
{
int ecount = 0;
for (int p = n; p > 0; p--)
{
ecount++;
if (arr[p] == x)
return ecount;
}
}
int superman(int arr[], int target)
{
int first = 0, last = n - 1, mid, pos = -1, coun = 0;
while (first <= last && pos == -1)
{
mid = (first + last) / 2;
if (arr[mid] == target)
pos = mid;
else if (target < arr[mid])
last = mid - 1;
else
first = mid + 1;
}
coun++;
if (pos != -1)
return coun;
}
int main()
{
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
int x;
cin >> x;
if (batman(arr, x) < cap(arr, x) && batman(arr, x) < superman(arr, x))
{
cout << "Batman";
}
else if (cap(arr, x) < batman(arr, x) && cap(arr, x) < superman(arr, x))
cout << "Captain America";
else if (superman(arr, x) < batman(arr, x)
&& superman(arr, x) < cap(arr, x))
cout << "Superman";
else
cout << "Batman" << endl << "Captain America" << endl << "Superman";
return 0;
}
I don't know what I am doing wrong. For some reason it doesn't compile on hackerrank, but it compiles on codeblocks. I also think that some of the answers I get are wrong but I can't put it on hackerrank.