Codeforces 626A Robot Sequence

A. Robot Sequence
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

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.

Output

Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.

Examples
input
6
URLLDR
output
2
input
4
DLUU
output
0
input
7
RLRLRLR
output
12
Note

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代表向右  问在这个字符串中有多少个子串可以满足回到起点的要求

题解:只要字符串中向上的次数等于向下的次数并且向左的次数等于向右的次数即可

#include<stdio.h>
#include<string.h>
#include<string>
#include<math.h>
#include<algorithm>
#define LL long long
#define PI atan(1.0)*4
#define DD doublea
#define MAX 1010
#define mod 10007
using namespace std;
char s[MAX]; 
int n;
int judge(int a,int b)
{
	int r,l,u,d,i,j;
	r=l=u=d=0;
	for(i=a;i<=b;i++)
	{
		if(s[i]=='U') u++;
		if(s[i]=='D') d++;
		if(s[i]=='L') l++;
		if(s[i]=='R') r++;
	}
	if(u==d&&l==r) return 1;
	else return 0;
}
int main()
{
    int j,i,sum;
    while(scanf("%d",&n)!=EOF)
    {
    	scanf("%s",s);
    	sum=0;
    	for(i=0;i<n;i++)
    	{
    		for(j=i+1;j<n;j++)
    		{
    			if(judge(i,j))
    			    sum++;
    		}
    	}
    	printf("%d\n",sum);
    }
	return 0;
} 

  

posted @ 2016-02-16 21:26  非我非非我  阅读(296)  评论(0编辑  收藏  举报