Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this ndays: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
4 1 3 2 0
2
7 1 3 3 2 1 2 3
0
2 2 2
1
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Source
Codeforces Round #363 (Div. 2)
My Solution
贪心+dp
//!从前往后, 前面的决定后面的, dp的思想, 前面处理完的时候前面部分是最优的了
如果第一位是 3, 第二位任意,直到出现一个1或者2
后面的如果是0还是0,如果是3就要相应的转化成1 或者 2
if(val[0] == 0) ans++;
对于 i = 1 ~ n-1
if(val[i] == 1 && val[i-1] == 1){
ans++;
val[i] = 0;
}
else if(val[i] == 2 && val[i-1] == 2){
ans++;
val[i] = 0;
}
else if(val[i] == 0) ans++;
else if(val[i] == 3){
if(val[i-1] == 1) val[i] = 2;
else if(val[i-1] == 2) val[i] = 1;
//!如果 val[i-1] == 0, 则任意, 对后面没有影响的 无论后面是 0 1 2 3
}
复杂度 O(n)
#include <iostream> #include <cstdio> using namespace std; typedef long long LL; const int maxn = 1e2 + 8; int val[maxn]; int main() { #ifdef LOCAL freopen("a.txt", "r", stdin); //freopen("b.txt", "w", stdout); int T = 3; while(T--){ #endif // LOCAL int n, ans = 0; scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d", &val[i]); } //!从前往后, 前面的决定后面的, dp的思想, 前面处理完的时候前面部分是最优的了 //!贪心+dp if(val[0] == 0) ans++; for(int i = 1; i < n; i++){ if(val[i] == 1 && val[i-1] == 1){ ans++; val[i] = 0; } else if(val[i] == 2 && val[i-1] == 2){ ans++; val[i] = 0; } else if(val[i] == 0) ans++; else if(val[i] == 3){ if(val[i-1] == 1) val[i] = 2; else if(val[i-1] == 2) val[i] = 1; //!如果 val[i-1] == 0, 则任意, 对后面没有影响的 无论后面是 0 1 2 3 } } printf("%d", ans); #ifdef LOCAL printf("\n"); } #endif // LOCAL return 0; }
Thank you!
------from ProLights