codeforces-370 B

86 篇文章 0 订阅

题意:

给出U D  L   R 询问最少调整多少个 字母,可以使上= 下  左=右  回到原点

思路:

如果是奇数个那必定不可能回到原点,

如果是偶数个,那么查找LR中大者   大的-1   建立 CHANGE  存放 如今可以转变的数量,  如果L!=R  那么L++  ,而L++的执行是CHANGE转变的。或者是当前R-- 转变成的S。原因是有可能 上或者下的 转变为左或者右。

先贴自己的垃圾代码。。再贴队友的代码。。下次多学习。。

#include <iostream>
#include <stdio.h>
#include <queue>
#include <stack>
#include <algorithm>
#include <cstring>
using namespace std;
int r=0,l=0,u=0,d=0;
char a[100010];

int main()
{

    gets(a);
    if(strlen(a)%2==1)
    {
        cout<<-1<<endl;
        return 0;
    }
    for(int i=0;i<strlen(a);i++)
    {
        if(a[i]=='R')
            r++;
        if(a[i]=='U')
            u++;
        if(a[i]=='L')
            l++;
        if(a[i]=='D')
            d++;
    }
    int change=0;
    int sum=0;
    while(l!=r)
    {
        if(l<r)
        {
            while(change!=0&&l!=r)
            {
                l++;
                change--;
            }
            if(r!=l)
            {
            sum++;
            r--;
            change++;
            }
        }
        if(r<l)
        {
            while(change!=0&&r!=l)
            {
                r++;
                change--;
            }
            if(r!=l)
            {
            sum++;
            l--;
            change++;
            }
        }
    }
    while(u!=d)
    {
        if(u>d)
        {
            while(change!=0&&u!=d)
            {
                d++;
                change--;
            }
            if(u!=d)
            {
                u--;
                change++;
                sum++;
            }
        }
        if(d>u)
        {
            while(change!=0&&u!=d)
            {
                u++;
                change--;
            }
            if(u!=d)
            {
                d--;
                change++;
                sum++;
            }
        }
    }
    cout<<sum<<endl;

    return 0;
}

队友的代码:

#include<iostream>
#include<string>
#include<cmath>
using namespace std;

string s;

int main()
{
int u,d,r,l;
while(cin>>s){
int ans = 0;
u = d = l = r =0;
for(int i = 0;i<s.length();i++){
if (s[i] == 'U') u++;
if (s[i] == 'D') d++;
if (s[i] == 'R') r++;
if (s[i] == 'L') l++;
}
if ((s.length() % 2)){
cout<<-1<<endl;
continue;
}
ans = 0;
if ((int)fabs(u-d) % 2){
if (l > r) r ++;
else l++;
if (u>d) u--;
else d--;
ans ++;
}
cout<<(fabs(d - u) / 2) + (fabs(l - r) / 2) + ans<<endl;
}
return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值