The while loop was sort of a mistake I made just before I posted the code here :x What's it called again, I think it was shotgun programming? I break stuff in trying to fix other things. Also, the problem says that I can assume that there is a solution. You have a good point though.
I fixed the loop fuckery to what it was and just replaced size with money. (could probably be money / 2 but w/e).
Anyway, it now works but isn't finding the correct solution, somehow. book1a and book2a are getting set with new values even though those new values are less optimal and I have a check in place to prevent this.
#include <iostream>
#include <vector>
using namespace std;
vector<int> books;
int findr(int value, int skip = -1);
int main()
{
while (true)
{
int totbooks;
int book1 = -1;
int book2 = -1;
int book1b = -1;
int book2b = -1;
cin >> totbooks;
for (int i = 0; i < totbooks; i++)
{
int book = 0;
cin >> book;
books.push_back(book);
}
int money;
cin >> money;
for (int i = 1; i < money; i++)
{
book1 = findr(i);
if (book1 == -1)
{
continue;
}
book2 = findr(money - books[book1], book1);
if (book2 == -1)
{
continue;
}
else if ((book1b == -1 && book2b == -1) || abs(books[book1] - books[book2]) < abs(books[book1b] - books[book2b]))
{
book1b = book1;
book2b = book2;
}
}
int abc = books[book2b];
int books1a = books[book1b];
if (abc > books1a)
{
int temp = abc;
abc = books1a;
books1a = temp;
}
cout << "Peter should buy books whose prices are ";
cout << abc;
cout << " and ";
cout << books1a;
cout << ".\n\n";
if (feof(stdin))
{
return 0;
}
books.clear();
}
}
int findr(int value, int skip)
{
for (int i = 0; i < books.size(); i++)
{
if (i == skip)
{
continue;
}
if (books[i] == value)
{
return i;
}
}
return -1;
}
Specifically, else if ((book1b == -1 && book2b == -1) || abs(books[book1] - books[book2]) < abs(books[book1b] - books[book2b]))
This should prevent book1b and book2b being set to new values if the new values give a larger price difference. Yet this input:
4
4 6 2 8
10
results in an output of 4 and 6. A breakpoint at the check tells me that the values are indeed being overwritten from 2 and 3 (positions in the vector) to 0 and 1.
I also don't see how book1 = findr(i) could be book1 = i;, since that gives no guarantee that said price is actually present. (it's probably an awful way to go about it, but it turns out im a terrible terrible terrible competetive programmer :c)