其他分享
首页 > 其他分享> > Zoj 1171 Sorting the Photos

Zoj 1171 Sorting the Photos

作者:互联网

题目描述

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