CF626A Robot Sequence (#模拟)

题面

CalvinCalvin 有一个机器人。这个机器人有U,D,L,R四个指令。

  • UU :向上移动一个单位长度
  • DD :向下移动一个单位长度
  • LL :向左移动一个单位长度
  • RR :向右移动一个单位长度

CalvinCalvin 给这个机器人随意输入了一串指令,并看着它缓缓移动。神奇的是最后机器人走回了起点。

现在CalvinCalvin 想知道,对于给定的一个长为nn 的命令序列,它有多少个不同的非空连续子序列,能使得机器人在执行这个子序列命令后能回到起点。两个子序列不同当且仅当它们在原给定序列中的起始位置不同或终止位置不同。

输入

  • 第一行一个正整数n (1 \le n \le 200)n(1≤n≤200) 表示命令序列长度。
  • 第二行一个长尾n的字符串表示命令序列。用字符U,D,L,R分别表示四种命令。

输出

仅一行一个整数表示答案。

感谢@frankchenfu 提供的翻译

题目描述

Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of nn 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, nn ( 1<=n<=2001<=n<=200 ) — the number of commands.

The next line contains nn 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.

输入输出样例

输入样例#1

6
URLLDR

输出样例#1

2

输入样例#2

4
DLUU

输出样例#2

0

输入样例#3

7
RLRLRLR

输出样例#3

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.


思路

这题其实没有黄题的难度吧。。

按照题意,只要向上与向下的次数相等并且向左或向右的次数相等就可以了,外面套2个循环,不断找子串,看能否匹配。

#include <stdio.h>
#include <iostream>
using namespace std;
int n,s;
char a[1001];
inline bool check(int l,int r)//能否匹配? 
{
	register int e,b,c,d,i;
	e=b=c=d=0;
	for(i=l;i<=r;i++)
	{
		if(a[i]=='U') e++;
		if(a[i]=='D') b++;
		if(a[i]=='L') c++;
		if(a[i]=='R') d++;
	}
	if(e==b && c==d)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	register int i,j,k;
	cin>>n>>a+1;
	for(i=1;i<=n;i++)//枚举左端点
	{
		for(j=i+1;j<=n;j++)//枚举右端点,这个就是不断找子串的过程 
		{
			if(check(i,j))
				s++;
		}
	}
	cout<<s<<endl;
	return 0;
} 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值