codeforces 712B Memory and Trident

B. Memory and Trident
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Examples
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.



首先,字符串的长度len肯定为偶数,否则不可能同时形成配对的U - D 和 R - L

设字符串中U,D,R,L的数量分别为cu,cd,cr,cl

t1 = cu + cd         t2 = cr + cl

在len为偶数的情况下,有两种情况:

1. t1和t2同时为奇

2. t1和t2同时为偶


同时为奇数的时候,则cu和cd尽可能平摊,多的一个给cr和cl,然后cr和cl再平摊,平摊的过程中记录变换的个数

同时为偶数的时候cu和cd直接平摊,cr和cl直接平摊就可以了,同样过程中记录变换的个数


#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <map>

using namespace std;

const int maxn = 100000;
char s[maxn + 5];
int len;

int main()
{
	int cu, cd, cr, cl, ans, t1, t2;
	scanf("%s", s);
	len = strlen(s);
	if (len % 2) {
		cout << -1 << endl;
		return 0;
	}
	map<char, int> m;
	for (int i = 0; i < len; i++) {
		m[s[i]]++;
	}
	cu = m['U'];
	cd = m['D'];
	t1 = cu + cd;
	cr = m['R'];
	cl = m['L'];
	t2 = cr + cl;
	if (t1 % 2 && t2 % 2) {
		ans = max(cu, cd) - t1 / 2;
		ans = ans + max(cl, cr) - (t2 + 1) / 2;
	} else if(t1 % 2 == 0 && t2 % 2 == 0) {
		ans = max(cu, cd) - t1 /2 + max(cl, cr) - t2 / 2;
	}
	cout << ans << endl; 
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值