๋ฌธ์ ์ค๋ช

๋์ ๊ณํ๋ฒ + ์ต๋จ๊ฑฐ๋ฆฌ ์ญ์ถ์ ๋ฌธ์ ์ด๋ค.
C++ ํ์ด
cpp#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; /* dp[i][i] ๊ฒฝ์ฐฐ์ฐจ 1์ด ๋ง์ง๋ง์ผ๋ก i๋ฒ์งธ ์ฌ๊ฑด ํด๊ฒฐ, ๊ฒฝ์ฐฐ์ฐจ 2๊ฐ ๋ง์ง๋ง์ผ๋ก j๋ฒ์งธ ์ฌ๊ฑด ํด๊ฒฐํ์ ๊ฒฝ์ฐ ์ด ๊ฑฐ๋ฆฌ์ ํฉ์ ์ต์๊ฐ ์ ์ฅ */ int N, M; pii accident[1001], before[1001][1001]; int dp[1001][1001]; int dist(int car, int start, int end){ if (start==0){ if (car==1){ return accident[end].first-1 + accident[end].second-1; } else { return N-accident[end].first + N-accident[end].second; } } // c++17 ๋ถํฐ ๊ฐ๋ฅ auto unpacking auto [x1, y1] = accident[start]; auto [x2, y2] = accident[end]; return abs(x1-x2)+abs(y1-y2); } void backtrace (int x, int y) { if (x==0 && y==0) return; int nx = before[x][y].first; int ny = before[x][y].second; backtrace(nx, ny); if (x>y) cout << "1\\n"; else cout << "2\\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin >> N >> M; for (int i=1; i<=M; i++){ cin >> accident[i].first >> accident[i].second; } // dp ์ด๊ธฐํ for(int i=0; i<=M; i++){ for (int j=0; j<=M; j++){ dp[i][j] = 1e9; } } dp[0][0]=0; // ์ฒ์์ ์์์ ์์ ์ด๋ํ๋ ๊ฒฝ์ฐ๋ง ๋ฐ๋ก ํด์ค์ผํจ for (int end=1; end<=M; end++){ // end-1์ ๊ฒฝ์ฐฐ์ฐจ1์ด ๋ฐฉ๋ฌธํ ๊ฒฝ์ฐ for (int car2=0; car2<=end-1; car2++){ // end๋ฅผ ๊ฒฝ์ฐฐ์ฐจ1์ด ๋ ๋ฐฉ๋ฌธ int dist11 = dp[end-1][car2] + dist(1, end-1, end); if (dist11<dp[end][car2]){ dp[end][car2] = dist11; before[end][car2] = {end-1, car2}; } // end๋ฅผ ๊ฒฝ์ฐฐ์ฐจ2๊ฐ ๋ฐฉ๋ฌธ int dist12 = dp[end-1][car2] + dist(2, car2, end); if(dist12 < dp[end-1][end]){ dp[end-1][end] = dist12; before[end-1][end] = {end-1, car2}; } } // end-1์ ๊ฒฝ์ฐฐ์ฐจ2์ด ๋ฐฉ๋ฌธํ ๊ฒฝ์ฐ for (int car1=0; car1<=end-1; car1++){ // end๋ฅผ ๊ฒฝ์ฐฐ์ฐจ2๊ฐ ๋ ๋ฐฉ๋ฌธ int dist22 = dp[car1][end-1] + dist(2, end-1, end); if(dist22<dp[car1][end]){ dp[car1][end] = dist22; before[car1][end] = {car1, end-1}; } // end๋ฅผ ๊ฒฝ์ฐฐ์ฐจ1์ด ๋ฐฉ๋ฌธ int dist21 = dp[car1][end-1] + dist(1, car1, end); if(dist21 < dp[end][end-1]){ dp[end][end-1] = dist21; before[end][end-1] = {car1, end-1}; } } } // ์ต๋๊ฐ ์ฐพ๊ธฐ int ans = 1e9; pii idx; for(int i=0; i<M; i++){ if (dp[M][i] < ans){ ans = dp[M][i]; idx = {M,i}; } if (dp[i][M] < ans){ ans = dp[i][M]; idx = {i,M}; } } cout << ans << '\\n'; backtrace(idx.first, idx.second); return 0; }
๋ง๋ฌด๋ฆฌ
DP ํ๋ํฐ๋ ๋ฌธ์ ์น๊ณค ๋์ ์์ด ํผ์ ์ ํ์ด๋๋ค. backtrace๋ ์๊ฐ๋ณด๋ค ์ฌ๋ฐ๋๊ฒ ๊ฐ๋ค.