zoukankan      html  css  js  c++  java
  • Codeforces Round #370 (Div. 2) B. Memory and Trident 水题

    B. Memory and Trident

    题目连接:

    http://codeforces.com/contest/712/problem/B

    Description

    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.

    Sample Input

    RRU

    Sample Output

    -1

    Hint

    题意

    修改最少的字符,使得这个机器人走回原点

    题解:

    从整体考虑,只要是偶数长度,那么一定有解。

    解就是L和R的绝对值+U和D的绝对值之差除以2,这个比较显然

    代码

    #include<bits/stdc++.h>
    using namespace std;
    
    int a[4];
    int main()
    {
        string s;
        cin>>s;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='L')a[0]++;
            if(s[i]=='R')a[1]++;
            if(s[i]=='U')a[2]++;
            if(s[i]=='D')a[3]++;
        }
        if(s.size()%2)
        {
            printf("-1
    ");
            return 0;
        }
        printf("%d
    ",(abs(a[0]-a[1])+abs(a[2]-a[3]))/2);
    }
  • 相关阅读:
    在 Java SE 6 中监视和诊断性能问题
    Codeforces Round #491 (Div. 2)部分题解
    BZOJ1607: [Usaco2008 Dec]Patting Heads 轻拍牛头(模拟 调和级数)
    BZOj1261: [SCOI2006]zh_tree(dp)
    BZOJ1569: [JSOI2008]Blue Mary的职员分配(dp 暴力)
    BZOJ4300: 绝世好题(dp)
    树上莫队算法
    SPOJ COT2
    BZOJ1086: [SCOI2005]王室联邦(贪心,分块?)
    Educational Codeforces Round 42 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5867807.html
Copyright © 2011-2022 走看看