1. 程式人生 > >Codeforces 712B Memory and Trident

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.

 

 

【題意】

Memory從原點開始,在二維平面上執行一次行走。他被賦予給一個帶有運動方向的字串s。

L、R、U、D分別表示向左、右、上、下移動一個單位。用L、R、U或D替換s中的任何字元

Memory想從原點出發再回到原點,至少改變字串中的幾個字元?如果無法回去,則返回-1。

【分析】

  倘若行走的單位數為奇數,對s的字元進行替換是無論如何都不會回到原點的。因為如果要回到原點,兩個點之間來回運動的單位數肯定是相等的,那麼總共是需要移動偶數次。所以當移動的次數是奇數時,直接輸出-1。

  L要有R抵消,U要有D抵消,需要改變的字元的數目就是所抵消的組數。左右改變次數為abs(L-R)/2,上下改變次數為abs(U-D)/2。  

【時間複雜度】 O(strlen(s))


【程式碼實現】

#include<stdio.h>
int main(){
    char s[10000];
    int len, i;
    int u=0, d=0, l=0, r=0;
    while(gets(s)){
        len = strlen(s);
        if(len%2==1) printf("-1\n");
        else{
            for(i = 0; s[i] != '\0'; i++){
                if(s[i]=='U') u++;
                else if(s[i]=='D') d++;
                else if(s[i]=='L') l++; 
                else if(s[i]=='R') r++;
            }
        printf("%d\n",(abs(u-d)+abs(l-r))/2);
        u=d=l=r=0;
        }
    }
    return 0;
}