ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Zoj 1171 Sorting the Photos

2022-04-09 18:02:09  阅读:161  来源: 互联网

标签:Sorting int Zoj number cin Photos str input line


题目描述

Imagine you have a pile of 1 <= N <= 10^5 photos. Some of them are faced upwards and the others faced downwards. Your goal is to sort them so all the photos are faced the same direction. The only operation you are allowed to do is to take any amount of the photos from the top into the separate pile, turn that pile upside-down as the whole and put it back over the rest of original pile.

Write the program that calculates the minimum number of such operations needed to complete the sorting goal.

This problem contains multiple test cases!

The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.

The output format consists of N output blocks. There is a blank line between output blocks.

Input

First line of the input contains the only number. Then, characters going possibly separated by newline and/or space characters "D" - faced down or "U" - faced up.

Output

Single integer number - minimal number of flip operations required to sort the photos pile.

样例

Sample Input

1

5
UU D
UU


Sample Output

2

算法1

(贪心) O(n)

1.输入处理:采用字符数组存储,cin可以过滤掉空格
2.核心思想:
(1)记录参考字符的位置,每次遇到与参考字符不一致的字符则将其前面的字符全部翻转,答案加1
(2)将该位置更新为参考位置
3.输出处理:zoj 是卡末尾空格的,最后一个样例结果输出时,需要特判一下

时间复杂度

线性扫描一遍,时间复杂度为O(n)

参考文献

某大佬博客

C++ 代码

#include <bits/stdc++.h>

using namespace std;
const int N = 1e5 + 10;
char str[N];
int t,n;

int solve()
{
	int pos = 0;  // 比较位置
	int res = 0;  // 记录翻转次数
	
	for(int i = 0; i < n; i ++)
	{
		if(str[i] != str[pos])
		{
			pos = i;
			res ++; 
		}
	} 
	
	return res;
}

int main ()
{
	cin >> t;
	
	while(t --)
	{
		cin >> n;
		
		for(int i = 0; i < n; i ++) cin >> str[i];
		
		cout << solve() << endl;
		if(t) cout << endl;
	}
	
	return 0;
}

标签:Sorting,int,Zoj,number,cin,Photos,str,input,line
来源: https://www.cnblogs.com/0wzh/p/16122880.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有