Codeforces 712B Memory and Trident
参考自:https://www.cnblogs.com/ECJTUACM-873284962/p/6375508.html
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
RRU
-1
UDUR
1
RUUR
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;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步