Memory and Trident

本文介绍了一个关于二维平面上行走的问题,目标是最小化修改指令序列所需的步骤,以便从任意起点回到原点。文章提供了一种解决方案,通过计算不同方向移动指令的数量差异来确定最少的修改次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Input

The first and only line contains the string s (1 ≤ |s| ≤ 100 000) — the instructions Memory is given.

Output

If 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
Note

In 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值