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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;
string fallingApart(vector<int>&, int&, int&);
void printEm(int, int);
void test(vector<int>&, int&, int&);
int main() {
int numPieces, alice, bob; //initializes variable for number of pieces integer breaks into
cin >> numPieces; // takes input for number of pieces
vector<int> v(numPieces);//initializes vector to the size input for number of pieces
for (auto& pieces : v) { //auto loop to fill vector with the values of the pieces
cin >> pieces;
}
fallingApart(v, alice, bob);
printEm(alice, bob);
test(v, alice, bob);
return 0;
}
string fallingApart(vector<int> &v, int &alice, int &bob) //function to sort, and have alice and bob take turns picking pieces.
{
sort(v.rbegin(), v.rend()); //stl sort of vector from first element to element past last element.
//descending order
alice = 0;//initialize alice to 0
bob = 0;//initialize bob to 0
for (int i = 0; i < v.size(); i++) { //for loop i starts at 0 checking to make sure that i
// is less than size of vector v.
if (i % 2 == 0) { //if statment to determine who's turn it is. if 2 modulo = 0 it's alices turn.
alice += v[i]; //if it's alices turn she takes the next number in the vector and adds it to her total
}
else {//modulo = 1 it's bobs turn
bob += v[i];//adds next number in vector to bobs total
}
}
return "alice << " " << bob";
//cout << alice << " " << bob << endl;// prints alices and bobs totals with a space inbetween
}
void printEm(int alice, int bob)
{
cout << alice << " " << bob << endl;
}
void test(vector<int> &v, int &alice, int &bob)
{
vector<int> x = { 4, 1, 2 };
assert(fallingApart(x, alice, bob) == "5 2");
vector<int> y = { 5, 3, 7, 8, 6 };
assert(fallingApart(y, alice, bob) == "17 12");
vector<int> z = { 6, 1, 1, 1, 4 };
assert(fallingApart(z, alice, bob) == "8 5");
cout << "all test cases passed!" << endl;
}
|