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.
#include<iostream>
#include<functional>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<cstdio>
#include<cmath>
#include<map>
using namespace std;
#define CRL(a) memset(a,0,sizeof(a))
typedef unsigned __int64 LL;
typedef __int64 ll;
#define CMP bool cmp(const node& a,const node& b){ return a.R<b.R||(a.R==b.R&&a.L<b.L); }
const int T = 503000;
const int mod = 1000000007;
struct node
{
int U,D,L,R;
friend void operator+(node& a,node& b){
a.D += b.D,a.L += b.L;
a.R += b.R,a.U += b.U;
}
}a[500];
void fun(char s,node& b)
{
if(s=='U')b.U++;
else if(s=='D')b.D++;
else if(s=='L')b.L++;
else b.R++;
}
bool jugde(node a,node b)
{
b.D -= a.D,b.L -= a.L;
b.R -= a.R,b.U -= a.U;
if(b.U==b.D&&b.L==b.R)
return true;
return false;
}
int main()
{
#ifdef zsc
freopen("input.txt","r",stdin);
#endif
int n,m,i,j,k;
char s[500];
while(~scanf("%d",&n))
{
memset(a,0,sizeof a);
scanf("%s",&s);
fun(s[0],a[1]);
for(i=1;i<n;++i){
fun(s[i],a[i+1]);
a[i+1] + a[i];
}
k = 0;
for(i=0;i<n;++i){
for(j=i+1;j<=n;++j){
if(jugde(a[i],a[j])){
k++;
}
}
}
printf("%d\n",k);
}
return 0;
}