zoukankan      html  css  js  c++  java
  • 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
    ",sum);
        }
    	return 0;
    } 
    

      

  • 相关阅读:
    c++ stringstream
    c语言中字符串数组初始化的一点总结&& c++访问控制的三种方式
    Leetcode 2. Add Two Numbers(medium)
    面试题---反转一个字符串
    编程题---在数组中取一个位置,让这个位置之前的数的和与之后的和的差绝对值最小
    美团面试准备
    Leetcode 101. Symmetric Tree(easy)
    Leetcode 665. Non-decreasing Array(Easy)
    617. Merge Two Binary Trees(Easy)
    423. Reconstruct Original Digits from English(Medium)
  • 原文地址:https://www.cnblogs.com/tonghao/p/5193867.html
Copyright © 2011-2022 走看看