LianLianKan(HDU-4272)(狀壓DP)

I like playing game with my friend, although sometimes looks pretty naive. Today I invent a new game called LianLianKan. The game is about playing on a number stack.
Now we have a number stack, and we should link and pop the same element pairs from top to bottom. Each time, you can just link the top element with one same-value element. After pop them from stack, all left elements will fall down. Although the game seems to be interesting, it's really naive indeed.


To prove I am a wisdom among my friend, I add an additional rule to the game: for each top element, it can just link with the same-value element whose distance is less than 6 with it.
Before the game, I want to check whether I have a solution to pop all elements in the stack.

Input

There are multiple test cases.
The first line is an integer N indicating the number of elements in the stack initially. (1 <= N <= 1000)
The next line contains N integer ai indicating the elements from bottom to top. (0 <= ai <= 2,000,000,000)

Output

For each test case, output “1” if I can pop all elements; otherwise output “0”.

Sample Input

2
1 1
3
1 1 1
2
1000000 1

Sample Output

1
0
0

Sponsor

 

題意:現在我們有了一個數字堆棧,我們應該從上到下鏈接並彈出相同的元素對。每次,您都可以將頂部元素與一個相同值的元素鏈接起來。將它們從堆棧中取出後,所有剩下的元素都會掉落。而且,每次可以選擇和棧頂一樣的數字,並且和棧頂距離小於6,然後同時消去他們,問能不能把所有的數消去。

思路:這道題的話,一個數字最遠能消去和他相距9的數,因爲中間4個可以被他上面的消去。因爲還要判斷棧頂有沒有被消去,所以10位dp。dp[i][j]表示第i個棧頂狀態爲j能否存在,用1表示某位被消去。那麼直接狀壓DP,假如被消去了則dp[i + 1][j >> 1] = 1。

AC代碼:

#include <bits/stdc++.h>
typedef long long ll;
const int maxx=1010;
const int inf=0x3f3f3f3f;
using namespace std;
int dp[maxx][1<<10];
int a[maxx];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=n; i>=1; i--)
            scanf("%d",&a[i]);
        if(n&1)
            printf("0\n");
        else
        {
            int b;
            memset(dp,0,sizeof(dp));
            dp[1][0]=1;
            for(int i=1; i<=n; i++)
            {
                b=min(10,n-i+1);
                for(int j=0; j<(1<<b); j++)
                {
                    if(dp[i][j]==0)
                        continue;
                    if(j&1)
                        dp[i+1][j>>1]=1;
                    else
                    {
                        int ans=0;
                        for(int k=1; k<b; k++)
                        {
                            if(!((1<<k)&j))
                            {
                                ans++;
                                if(ans<6 && a[i]==a[i+k])
                                {
                                    int cnt=j|(1<<k);
                                    dp[i+1][cnt>>1]=1;
                                }
                            }
                        }
                    }
                }
            }
            printf("%d\n",dp[n][1]);
        }
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章