반응형
https://www.hackerrank.com/challenges/kangaroo/problem
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
/*
* Complete the 'kangaroo' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. INTEGER x1
* 2. INTEGER v1
* 3. INTEGER x2
* 4. INTEGER v2
*/
string kangaroo(int x1, int v1, int x2, int v2) {
// case where one will never be able to catch up the other
if (v1 <= v2) return "NO";
// they have to arrive at the same place 'at the same time',
// so they should have jumped the same amount when they meet
// x1 + v1*i = x2 + v2*i
// i = (x2 - x1)/(v1 - v2)
for (int i = 0;; i++) {
if ((x2 - x1) % (v1 - v2) == 0) return "YES";
// cases where one goes past the other without meeting
if (((v1 <= v2) && (x1 + v1 * i) < (x2 + v2 * i))
|| ((v1 >= v2) && (x1 + v1 * i) > (x2 + v2 * i))) return "NO";
}
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string first_multiple_input_temp;
getline(cin, first_multiple_input_temp);
vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));
int x1 = stoi(first_multiple_input[0]);
int v1 = stoi(first_multiple_input[1]);
int x2 = stoi(first_multiple_input[2]);
int v2 = stoi(first_multiple_input[3]);
string result = kangaroo(x1, v1, x2, v2);
fout << result << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
Testcase
Input
43 2 70 2
Output
NO
반응형
'Training > HackerRank' 카테고리의 다른 글
[C++][Introduction] Pointer (0) | 2021.08.03 |
---|---|
[C++][Implementation] Breaking the Records (0) | 2021.08.01 |
[C++][Implementation] Apple and Orange (0) | 2021.07.28 |
[C++][Implementation] Grading Students (0) | 2021.07.19 |
[C++][Warmup] Time Conversion (0) | 2020.09.06 |