개인적으로 생각하기 좀 어렵고 번거로웠던 문제이다. 치는공과 맞춰야하는 공의 위치를 잘 선정해서 풀면 쉽게 풀수 있다. 필자의 풀이는 별로이니 아래 코드를 참고하는것을 추천한다...
#include <string>
#include <vector>
using namespace std;
int pow(int n)
{
return n*n;
}
vector<int> solution(int m, int n, int startX, int startY, vector<vector<int>> balls)
{
vector<int> answer;
int cnt = balls.size();
for(int i=0;i<cnt;i++)
{
int len, a, b;
if (balls[i][0] == startX)
{
a = abs(startY - balls[i][1]);
b = 2 * min(m - startX, startX);
if (startY > balls[i][1]) len = pow(a + 2*(n - startY));
else len = pow(a + 2*startY);
}
else if(balls[i][1] == startY)
{
a = abs(startX - balls[i][0]);
b = 2 * min(n - startY, startY);
if (startX > balls[i][0]) len = pow(a + 2*(m - startX));
else len = pow(a + 2*startX);
}
else
{
a = min(startX + balls[i][0], 2*m - startX - balls[i][0]);
b = abs(startY - balls[i][1]);
len = pow(a) + pow(b);
a = min(startY + balls[i][1], 2*n - startY - balls[i][1]);
b = abs(startX - balls[i][0]);
}
len = min(len, pow(a) + pow(b));
answer.push_back(len);
}
return answer;
}
좋아보였던 풀이!!!
#include <cmath>
#include <vector>
#include <climits>
using namespace std;
int calc_dist(int m, int n, int a, int b, int c, int d)
{
int total=INT_MAX;
if(a!=c || b<=d) total=min(total, (int)(pow(a-c, 2)+pow(b+d, 2)));
if(a>=c || b!=d) total=min(total, (int)(pow(a-2*m+c, 2)+pow(b-d, 2)));
if(a!=c || b>=d) total=min(total, (int)(pow(a-c, 2)+pow(b-2*n+d, 2)));
if(a<=c || b!=d) total=min(total, (int)(pow(a+c, 2)+pow(b-d, 2)));
return total;
}
vector<int> solution(int m, int n, int startX, int startY, vector<vector<int>> balls)
{
vector<int> answer;
for(int i=0; i<balls.size(); i++)
answer.push_back(calc_dist(m, n, startX, startY, balls[i][0], balls[i][1]));
return answer;
}