HDU-4272 LianLianKan (DFS)

That Italy: multiple test samples, N elements (1 <= N <= 1000 ), each element value (0 <= ai <= 2,000,000,000 ), which elements are pushed onto the stack, the stack same It can be eliminated together (each connected to the same top distance must be less than 6), and finally asked whether the entire stack can pop
ideas: with dfs recursively search for possible solutions
regarding the deletion (beginning with the list but think of the feeling by location delete so much trouble with vis [] array simulation)
(optimized): If n is odd also eliminates endless (no match), if the number is an odd number, then the stack absolute bomb could not finish, so this would Some can predict in advance. (We can use the map to count the number of each number)

Complete code:

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<map>

using namespace std;

int vis[1001],a[1001];

int dfs(int n)
{
    int i=0,j=n-1;
    while(n>=0&&vis[n]) --n;
    if(n==-1) return 1;
    if(n==0&&!vis[0]) return 0;
    while(i<=5)
    {
        if(j<0) return 0;
        if(vis[j]) --j;
        if(a[n]==a[j])
        {
            vis[j]=1;
            if(dfs(n-1)) return 1;
            vis[j]=0;
        }
        ++i;
        --j;
    } 
    return 0;
}

int main()
{
    int k,m,q,t,p,n;
    int T;
    map<int,int> mp;
    map<int,int>::iterator it;
    
    while(cin>>n)
    {
        
        t=0;
        for(int i=0;i<n;++i)
        {
            scanf("%d",&a[i]);
            vis[i]=0;
            mp[a[i]]++;
        }
        if(n&1) {
            cout<<0<<endl;
            continue; 
        }
        
        for(it=mp.begin();it!=mp.end();++it)
        {
            if((*it).second%2)
            {
                t=1;
                break;
            }
        }
        
        if(t)
        {
            cout<<0<<endl;
        }else
        {
            cout<<dfs(n-1)<<endl;
        }

    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/Tianwell/p/11225162.html
dfs