HDU 4272 LianLianKan DFS+map优化

LianLianKan

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2694    Accepted Submission(s): 830


Problem Description
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
 


不用map 优化的话,会TLE。

#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#define  N 2000
using namespace std;
int a[N];
map<int ,int>mp;
int vis[N];

int dfs(int n)
{
    while(vis[n]&&n>0) n--;
    if(n==0) return 1;//全部消除完
    if(n==1) return 0;//还剩下一个

    int j=n-1;

    for(int k=0;k<5;)
    {
        if(j<=0) return 0;
        if(vis[j]) {j--;continue;}

        if(a[j]==a[n])
        {
            vis[j]=1;
            if(dfs(n-1))  return 1;
            vis[j]=0;

        }
        k++;
        j--;
    }

    return 0;
}

int main()
{

    int n;
    while(~scanf("%d",&n))
    {
        mp.clear();
        for(int i=1;i<=n;i++)
        {
            scanf("%I64d",&a[i]);
            mp[a[i]]++;
        }

        if(n%2)
        {
            cout<<0<<endl;
            continue;
        }

        map<int,int>::iterator it;
        int flag=1;

        for(it=mp.begin();it!=mp.end();it++)
        {
            if((it->second)%2)
            {
                flag=0;
                break;
            }
        }

        if(flag==0)
        {
            cout<<0<<endl;
            continue;
        }
        memset(vis,0,sizeof vis);

        printf("%d\n",dfs(n));

    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值