Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
6
URLLDR
2
4
DLUU
0
7
RLRLRLR
12
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
题意:在一块方格里,给出一串指令包含U,D,L,R这些字母,分别表示上下左右移动一格。问有多少个子串(包含自身)能使得物体回到出发位置。
题解:n的大小才200,直接暴力。
代码如下:
#include<cstdio>
#include<cstring>
char str[210];
int main()
{
int n,i,j,u,d,l,r,ans;
while(scanf("%d",&n)!=EOF)
{
scanf("%s",str);
ans=0;
for(i=0;i<n;++i)
{
u=0; d=0; l=0; r=0;
for(j=i;j<n;++j)
{
if(str[j]=='U')
u++;
if(str[j]=='D')
d++;
if(str[j]=='L')
l++;
if(str[j]=='R')
r++;
if(u==d&&r==l)
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}