4. hoof prints
Title Description
topic:
虽然当奶牛贝里斯找到平衡序列后很高兴了,但是他现在对序列提出了一个更高的要求,就是要求每个序列中必须是先一定数量的左括号然后是与左括号相同数量的右括号。例如:(((()))),就是一个完美的平衡序列。
当贝里斯某天在农场上走的时候,他在地上发现了马蹄印,这个农场是一个N*N的方格,每个小方格中都有一个马蹄印。贝里斯希望从方格的最左上角的地方开始出发,然后每次可以向上或者向下或者向左或者向右移动一步,使得他走过的每个小方格中的马蹄印能够组成一个完美的平衡序列。当然了,贝里斯不能重复经过任何小方格。
Problem Description:
请帮助贝里斯在这个N*N的方格中找出长度最长的完美序列的长度。
Entry
The first line of a positive integer N, the size of the farm.
Next N lines of N characters, represents the distribution of the N * N squares of marks going.
Export
只有一行一个整数,表示最长的完美序列的长度,如果不存在这样的完美序列(例如起始位置就是右括号),则输出0。
Sample input
4
(())
()((
(()(
))))
Sample Output
8
Data range limit
Data range: 2 <= N <= 5.
Positive solutions
to see that this is DFS, deep search
AC Code
#include<iostream>
#include<cstdio>
using namespace std;
int n,a[10][10],m;
int dx[5]={0,-1,1,0,0};
int dy[5]={0,0,0,-1,1};
char ch;
void dfs(int x,int y,int l,int r)
{
if(l==r){m=max(m,l+r);return;}
if(l<r)return;
for(int i=1;i<=4;i++)//遍历四个方向
{
int xx=x+dx[i],yy=y+dy[i];
if(xx>=1&&xx<=n&&yy>=1&&yy<=n&&a[xx][yy]!=2)//边界和有没有走过的判断
if(a[xx][yy]==0)
{
if(r==0)//必须要判断‘)’没有出现过才能找‘(’
{
a[xx][yy]=2;//标记
dfs(xx,yy,l+1,r);
a[xx][yy]=0;//回溯
}
}
else
{
a[xx][yy]=2;//标记
dfs(xx,yy,l,r+1);
a[xx][yy]=1;//回溯
}
}
}
int main()
{
freopen("hshoe.in","r",stdin);
freopen("hshoe.out","w",stdout);
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
cin>>ch;
if(ch==')')a[i][j]=1;
}
if(a[1][1]==1)cout<<0;//如果第一个是‘)’就直接退出
else{a[1][1]=2;dfs(1,1,1,0);cout<<m;}
return 0;
}
Other topics is attached below the tournament
2020.02.13 universal simulation game C 6 group (the first question)
2020.02.13 universal simulation game C 6 group (the second question)
2020.02.13 universal simulation game C 6 group (third problem)
2020.02.13 simulation game popularity group C 6 (fourth question)
2020.02.13 popularity in group C simulation game 6 (summary)