※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 11291번 문제인 Alicia's Afternoon Amble이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/11291 

 

11291번: Alicia’s Afternoon Amble

The (x, y) coordinates of all locations are given as integers on a Euclidean plane. The first line of input contains a single integer n, 1 ≤ n ≤ 1000, representing the number of locations. Each of the next n lines contains two integers x and y, 0 ≤ x

www.acmicpc.net

각 장소에 x좌표 오름차순으로 0부터 N-1까지의 index를 부여하자.

 

그리고 \(dp[i][j]\) (단, \(i<j\))를 "장소 0부터 장소 i까지 가는, 경유하는 장소의 x좌표가 오름차순인 경로 \(P1\)과 장소 0부터 장소 j까지 가는, 경유하는 장소의 x좌표가 오름차순인 경로 \(P2\)가 있을 때 아래의 조건을 만족하는 두 경로에 대하여 그 경로의 길이의 합의 최솟값으로 정의하자.

\(P1\)을 구성하는 장소와 \(P2\)를 구성하는 장소는 장소 0을 제외하고 서로 다르면서 둘을 구성하는 장소의 합집합은 j 이하의 장소를 모두 포함하고 있어야 한다.

이 때 \(i\)와 \(j\)의 차가 2 이상이라면 \(dp[i][j] = dp[i][j-1] + dist(j-1, j)\) 와 같이 계산할 수 있음을 알 수 있다. 

\(i+1=j\)이면 \(dp[i][j] = min(dp[k][j-1] + dist(k,j))\) (단, \(k<j-1\))와 같이 계산할 수 있다.

 

또한 문제의 답은 \(min(dp[k][N-1]+dist(k,N-1))\) (단, \(k<N-1\))와 같이 계산할 수 있다.

 

위의 점화관계를 이용해 문제를 해결하자.

 

아래는 제출한 소스코드이다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
typedef long double ld;

int N;
vector<pair<ll, ll>> vec;

vector<ld> dp(1000);
vector<ld> tmp(1000);

ld dist(pair<ll, ll>& p1, pair<ll, ll>& p2) {
	return hypot((ld)(p2.first - p1.first), (ld)(p2.second - p1.second));
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cout << fixed;
	cout.precision(2);

	cin >> N;
	for (int i = 0; i < N; i++) {
		ll x, y; cin >> x >> y;
		vec.emplace_back(make_pair(x, y));
	}

	sort(vec.begin(), vec.end());

	if (N == 1) cout << 0;
	else {
		dp[0] = dist(vec[0], vec[1]);
		for (int i = 2; i < N; i++) {
			ld dd = dist(vec[i - 1], vec[i]);
			tmp[i - 1] = 1000000000000000007LL;
			for (int j = 0; j < i - 1; j++) {
				tmp[j] = dp[j] + dd;
				tmp[i - 1] = min(tmp[i - 1], dp[j] + dist(vec[j], vec[i]));
			}

			swap(dp, tmp);
		}

		ld ans = 1000000000000000007LL;
		for (int i = 0; i < N - 1; i++) {
			ans = min(ans, dp[i] + dist(vec[i], vec[N - 1]));
		}
		
		cout << ans;
	}
}

 

728x90

+ Recent posts