/* ListeningSongs (SRM 679, D2, 250 from Topcoder). James S. Plank Tue Sep 13 23:10:05 EDT 2016 */ #include #include #include #include #include #include #include #include #include #include using namespace std; class ListeningSongs { public: int listen(vector durations1, vector durations2, int minutes, int T); }; int ListeningSongs::listen(vector durations1, vector durations2, int minutes, int T) { int i; int d; int rv; int seconds; vector FD; seconds = minutes * 60; /* Part 1 -- Exit if either album has fewer than T songs. */ if (durations1.size() < T) return -1; if (durations2.size() < T) return -1; /* Part 2: Sort the two albums, and sum up the duration of the T shortest songs on each album. */ sort(durations1.begin(), durations1.end()); sort(durations2.begin(), durations2.end()); d = 0; for (i = 0; i < T; i++) { d += durations1[i]; d += durations2[i]; } /* If that duration is too big, return -1. Otherwise, subtract that duration from the total number of seconds that you can listen to songs. */ if (d > seconds) return -1; seconds -= d; /* Part 3: Create a new vector, FD, from the remaining songs on each album */ for (i = T; i < durations1.size(); i++) FD.push_back(durations1[i]); for (i = T; i < durations2.size(); i++) FD.push_back(durations2[i]); /* Sort it, and then run through it, seeing if you can listen to each song. If not, you return. If you get to the end of the vector, you can listen to all of the songs! */ rv = T*2; /* This is our return value, which starts at T*2 */ sort(FD.begin(), FD.end()); for (i = 0; i < FD.size(); i++) { seconds -= FD[i]; if (seconds < 0) return rv; rv++; } return rv; }