您的位置:首页 > 其它

Memory and Trident

2018-03-19 18:10 253 查看
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion:
An 'L' indicates he should move one unit left.
An 'R' indicates he should move one unit right.
A 'U' indicates he should move one unit up.
A 'D' indicates he should move one unit down.
But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.
InputThe first and only line contains the string s (1 ≤ |s| ≤ 100 000) — the instructions Memory is given.
OutputIf there is a string satisfying the conditions, output a single integer — the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.
Example Input
RRU
Output
-1
Input
UDUR
Output
1
Input
RUUR
Output
2
NoteIn the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.
In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin.
题意:有四种命令:U代表上移一个单位,D代表下移一个单位,R代表右移一个单位,L代表左移一个单位。
现在给出一串命令,问怎样修改命令中的任意一条命令,使得命令结束后重新返回原点,并且修改的步数最少。
思路:把问题抽象化,统计四中命令各自有多少,之后D与U相互抵消(numD-numU),R与L相互抵消(numR-numL),将两个差值的绝对值相加之后除以二就是结果。
例如:DUDRLRRUDL
D命令有numD=3条
U命令有numU=2条
R命令有numR=3条
L命令有numL=2条
|numD-numU|=1;|numR-numL|=1;
证明在抵消完所有能抵消的命令之后只剩下一条D命令和一条R命令,所以只需修改R为U即可,
答案就是(|numD-numU|+|numR-numL|)/2=1;
我们还发现,当字符串的长度是奇数的时候不存在解,无法完全抵消。#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
char s[100005];
cin>>s;
int n=strlen(s);
int numL=0;
int numR=0;
int numU=0;
int numD=0;
for(int i=0;i<n;i++)
{
if(s[i]=='L')
numL++;
if(s[i]=='R')
numR++;
if(s[i]=='U')
numU++;
if(s[i]=='D')
numD++;
}
if(n%2==0)
{
int sum=(abs(numL-numR)+abs(numU-numD))/2;
cout<<sum<<endl;
}
else
cout<<"-1"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: