Description
Memory is performing a walk on the two-dimensional plane, and starting at the origin. He is given a string s with his directions for motion:
- A '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-end at the origin. To does 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 me Memory what's the minimum number of changes he needs to make to produce a string that when walked, would end At the origin, or if there is no such string.
Input
The first and only line contains the string s (1≤| S| ≤100)-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-it'll bring Memory to the origin, output -1.< /c0>
Sample Input
Input
RRU
Output
-1
Input
Udur
Output
1
Input
Ruur
Output
2
Hint
In the first sample test, the Memory was told to walk right and then right and then up. It is an easy-to-see, it is impossible-to-edit these instructions to form a valid walk.
In the second sample test, the Memory was told to walk up, then down, then up and 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.
Problem: Water.
The code is as follows:
1#include <iostream>2#include <cstdio>3#include <cstdlib>4#include <cstring>5#include <string>6#include <cmath>7#include <map>8#include <stack>9#include <vector>Ten#include <queue> One#include <Set> A#include <algorithm> - #defineMax (A, B) (A>B?A:B) - #defineMin (A, b) (A<B?A:B) the #defineSwap (A, b) (A=a+b,b=a-b,a=a-b) - #defineMAXN 320007 - #defineN 100000000 - #defineINF 0x3f3f3f3f + #defineMoD 1000000009 - #defineE 2.718281828459045 + #defineEPS 1.0e18 A #definePI ACOs (-1) at #defineLowbit (x) (x& (×)) - #defineRead (x) scanf ("%d", &x) - #definePut (x) printf ("%d\n", X) - #definememset (x, y) memset (x,y,sizeof (×)) - #defineDebug (x) cout<<x<< "" <<endl - #defineLson I << 1,l,m in #defineRson I << 1 | 1,m + 1,r - #definell Long Long to //Std::ios::sync_with_stdio (false); + //Cin.tie (NULL); - using namespacestd; the * Chara[111111]; $ intb[4];Panax Notoginseng intMain () - { theCin>>A; + intL=strlen (a); A if(l%2) the { +cout<<"-1"<<Endl; - return 0; $ } $ for(intI=0; i<l;i++) - { - if(a[i]=='L') theb[0]++; - if(a[i]=='R')Wuyib[0]--; the if(a[i]=='U') -b[1]++; Wu if(a[i]=='D') -b[1]--; About } $ //cout<<b[0]<< "" <<b[1]<<endl; -cout<< (ABS (b[0]) +abs (b[1]))/2<<Endl; - return 0; -}
View Code
Memory and Trident (Codeforces 712B)