954A. Diagonal Walking C++

本文解析了一个简化路径算法的问题,该问题来源于CodeForces竞赛平台的一个A级别题目。通过分析移动序列(R-U右上移动,D对角线移动),介绍了如何将原始序列简化为最短有效步骤的方法,并提供了详细的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:http://codeforces.com/contest/954/problem/A

题目:

Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.

In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.

Your problem is to print the minimum possible length of the sequence of moves after the replacements.

Input

The first line of the input contains one integer n (1 ≤ n ≤ 100) — the length of the sequence. The second line contains the sequence consisting of n characters U and R.

Output

Print the minimum possible length of the sequence of moves after all replacements are done.

Examples
input
Copy
5
RUURU
output
3
input
Copy
17
UUURRRRRUUURURUUU
output
13
Note

In the first test the shortened sequence of moves may be DUD (its length is 3).

In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13).

思路:

挺简单的一题。R U RU UR都算一步,如果RR就是两步,RRU是两步。好了,题目意思相信你们能看懂了。

然后我是用字符数组实现的。判断一个字符和它之后的字符,如果相等就往下再判断一个,同时总和加一。如果不同,就跳一个判断,同时总和加一。因为考虑到i+1溢出的情况,所以实现判断。如果到了最后一个字符时,说明它前面并没有匹配的小伙伴,于是总和加一。

代码:

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        string a;
        cin>>a;
        int i,k=0;
        int h=a.length();
        for(i=0;i<h;)
        {
           if(i+1>=h){k=k+1;break;}
           else{
           if(a[i]=='R'&&a[i+1]=='R')k=k+1,i++;
           else if(a[i]=='R'&&a[i+1]=='U')k=k+1,i=i+2;
           if(a[i]=='U'&&a[i+1]=='U')k=k+1,i++;
           else if(a[i]=='U'&&a[i+1]=='R')k=k+1,i=i+2;}
        }
        cout<<k<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值