zcmu-1279 Sort photos(仔细读题)

本文介绍了一个有趣的算法问题:如何通过最少的操作将一堆照片全部翻转到同一面。问题设定为给定一组面向上或下的照片,只能翻转方向一致的照片,目标是最小化翻转次数。文章提供了一个C++实现的示例,展示了如何通过比较连续不同方向照片的数量来找到最小翻转数。

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

 Description

Imagine you have a pile of n photos. Some of them are faced upwards and the others faced downwards. Your goal is to sort them so that all the photos are faced the same direction. The only operation you are allowed to do is to take any amount of the photos if their direction is same to the other direction. Write the program that calculates the minimum number of such operations needed to complete the sorting goal.

Input

There are multiple test cases in the input file.
For each test case, the first line is n (0<n<10^5) - the number of photos.
The second line is n characters "D" - faced down or "U" - faced up.

Output

For each test case there is a single integer number - minimal number of flip operations required to sort the photos pile.

Sample Input

5

UUDUU

4

UDUD

Sample Output

1

2

仔细读红字部分 

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

int main() {
    int n;
    char str[100005];
    while(scanf("%d",&n)!=EOF)
    {
        int x = 0,y = 0;
        scanf("%s",str);
        int len = strlen(str);
        for(int i = 0; i < len;i++)
        {
            if(str[i] == 'U' && str[i + 1] != 'U')
                x ++;
            if(str[i] == 'D' && str[i + 1] != 'D')
                y ++;
        }
        printf("%d\n",min(x,y));
    }
    return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值