題面鏈接
http://acm.hdu.edu.cn/showproblem.php?pid=4272
題面
題意
一個棧,每次可以選擇和棧頂一樣的數字,並且和棧頂距離小於,然後同時消去他們,問能不能把所有的數消去。
思路
每個數字最遠能消去和他相距的數,因爲至多中間個可以被他上面的消去。然後還要判斷棧頂有沒有被消去,所以開位。表示第個棧頂狀態爲是否存在。那麼直接狀壓,假如被消去了就。
!注意給定的是正確的進棧順序。
參考代碼
/* CF was purple years ago!
* Thanks cf-tool!
* Author: nuoyanli
* Time: 2020-02-29 21:05:05
**/
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false), cin.tie(0)
#define endl '\n'
#define PB push_back
#define FI first
#define SE second
#define m_p(a, b) make_pair(a, b)
#define lson l, mid, root << 1
#define rson mid + 1, r, root << 1 | 1
#define T(t) while (t--)
#define inf 0x3f3f3f3f
typedef long long LL;
const double pi = acos(-1.0);
const double eps = 1e-9;
const int N = 2e6 + 10;
const int M = 1e5 + 10;
const int mod = 1e9 + 7;
const int st = (1 << 10);
int dp[st][st], a[st]; // dp[i][j]表示第i個棧頂狀態爲j是否存在
void solve() {
IOS;
int n;
while (cin >> n) {
for (int i = n; i >= 1; i--) {
cin >> a[i];
}
if (n & 1) { //顯然奇數必不可消完
cout << 0 << endl;
} else {
int limt = 0;
fill(dp[0], dp[0] + st * st, 0); // fill 二維數組初始化
dp[1][0] = 1;
for (int i = 1; i <= n; i++) {
limt = min(10, n - i + 1); //控制上限可以省時間23333
for (int j = 0; j < (1 << limt); j++) {
if (!dp[i][j]) { //如果狀態不存在
continue;
}
if (j & 1) { //消去了
dp[i + 1][j >> 1] = 1;
} else {
int num = 0; //至多往下5位
for (int k = 1; k < limt; k++) {
if (!((1 << k) & j)) {
num++;
if (a[i] == a[i + k] && num < 6) { //滿足即消去
dp[i + 1][(j | (1 << k)) >> 1] = 1;
}
}
}
}
}
}
cout << dp[n][1] << endl;
}
}
}
signed main() {
solve();
return 0;
}