You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<cstring>
#defineSIZE100000+1
#defineSTEP4+1
#defineINF1000000usingnamespacestd;int arr[SIZE];
int dp[SIZE][STEP][STEP];
intcalc(int a, int b) {
if (a == b) return1;
if (a == 0 || b == 0) return2;
if (a < b) swap(a, b);
if (a == 4 && b == 1) {
return3;
}
return a - b + 2;
}
voidsolution() {
int num, N = 0;
for (int i = 1;; i++) {
cin >> num;
if (num == 0) break;
arr[i] = num;
N++; // count of nums in arr (it also means last index of arr)
}
memset(dp, INF, sizeof(dp));
dp[1][arr[1]][0] = 2;
dp[1][0][arr[1]] = 2;
dp[0][0][0] = 0;
for (int i = 2; i <= N; i++) {
for (int left = 0; left <= 4; left++) {
for (int right = 0; right <= 4; right++) {
if (left == right) continue;
if (left != arr[i] && right != arr[i]) continue;
for (int next = 0; next <= 4; next++) {
if (left == arr[i]) dp[i][left][right] = min(dp[i][left][right], dp[i - 1][next][right] + calc(next, left));
if (right == arr[i]) dp[i][left][right] = min(dp[i][left][right], dp[i - 1][left][next] + calc(next, right));
}
}
}
}
int answer = 1000000;
for (int step = 0; step <= 4; step++) {
if (step == arr[N]) continue;
answer = min(answer, dp[N][arr[N]][step]);
answer = min(answer, dp[N][step][arr[N]]);
}
if (answer >= 1000000) {
answer = 0;
}
cout << answer << "\n";
}
intmain() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
solution();
return0;
}
Activity