HDU4272LianLianKan(dfs)

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. 
HDU4272LianLianKan(dfs)
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
 
 
Source

注意给的顺序是从底部到顶部。

开始想直接模拟,不可行,因为在下面5个里可能有一个或多个相同的元素,每个选择都可能对后面造成影响,因此要dfs。

其中还巧妙的用了map,当然改用set来存然后看里面到底有没有奇数个的元素也是可以的,这点的优化很重要。

 #include<stdio.h>
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<set>
#include<map> using namespace std; int vis[],a[]; int dfs(int n)
{
int i=,j=n-;
while(n>=&&vis[n]) --n;
if(n==-) return ;
if(n==&&!vis[]) return ;
while(i<=)
{
if(j<) return ;
if(vis[j]) --j;
if(a[n]==a[j])
{
vis[j]=;
if(dfs(n-)) return ;
vis[j]=;
}
++i;
--j;
}
return ;
} int main()
{
int k,m,q,t,p,n;
int T;
map<int,int> mp;
map<int,int>::iterator it; while(cin>>n)
{
t=;
for(int i=;i<n;++i)
{
scanf("%d",&a[i]);
vis[i]=;
mp[a[i]]++;
} for(it=mp.begin();it!=mp.end();++it)
{
if((*it).second%)
{
t=;
break;
}
} if(t)
{
cout<<<<endl;
}else
{
cout<<dfs(n-)<<endl;
} }
return ;
}
上一篇:linux系统--磁盘管理命令(二)


下一篇:c++ 调用外部程序exe-ShellExecuteEx