E - Memory and Trident
CodeForces - 712B
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.
題意:最少改變幾次移動,使最終回到原點收捣。
解法:移動次數(shù)為單數(shù)不可能回到原點调鲸。不為單數(shù)時上x+1像云,下x-1怖现,左y+1蕴茴,右y-1琉预,最后x和y的絕對值相加除以二董饰。
代碼:
#include<iostream>
#include<cstring>
#include<math.h>
#include<cmath>
using namespace std;
int main()
{
int a=0,b=0;
char c[100000];
cin>>c;
int n=strlen(c);
if(n%2==1)
cout<<-1<<endl;
else{
for(int i=0;i<n;i++){
if(c[i]=='U')
a++;
else if(c[i]=='D')
a--;
else if(c[i]=='L')
b++;
else
b--;
}
cout<<(abs(a)+abs(b))/2<<endl;
}
return 0;
}