2012-06-22 19:42:52Morris

[UVA] 12416 - Excessive Space Remover

Problem E

Excessive Space Remover

How do you remove consecutive spaces in a simple editor like notepad in Microsoft Windows? One way is to repeatedly "replace all" two consecutive spaces with one space (we call it an action). In this problem, you're to simulate this process and report the number of such "replace all" actions.

For example, if you want to remove consecutive spaces in "A very big joke.", you need two actions:

"A very  big    joke." -> "A very big  joke." -> "A very big joke."

Input

The input contains multiple test cases, one in a separate line. Each line contains letters, digits, punctuations and spaces (possibly leading spaces, but no trailing spaces). There will be no TAB character in the input. The size of input does not exceed 1MB.

Output

For each line, print the number of actions that are required to remove all the consecutive spaces.

Sample Input

A very  big    joke.
         Goodbye!

Output for Sample Input

2
4

Explanation

If you can't see clearly, here is the sample input, after replacing spaces with underscores:
A*very**big****joke.
*********Goodbye!


#include <stdio.h>
char s[1000000];
int main() {
while(gets(s)) {
int cnt = 0, max = 0, i;
for(i = 0; s[i]; i++) {
if(s[i] == ' ')
cnt++;
else {
if(cnt > max)
max = cnt;
cnt = 0;
}
}
cnt = 0;
while(max != 1) {
cnt++;
max = max/2 + (max-max/2*2);
}
printf("%d\n", cnt);
}
return 0;
}

Zero 2012-10-07 15:59:52

看到了那句話,我終於明白題目的意思了,謝啦~

Zero 2012-10-07 14:26:23

不好意思,請問一下
while(max != 1) {
cnt++;
max = max/2 + (max-max/2*2);
}
這段可以講解一下嗎?

我一直覺得max = max/2 + (max-max/2*2);這一行跟 max/2 好像是一樣的

而且我不太懂題目的意思
如果有一行前8格是空白最後補一個a,那答案應該是8-2 > 6-2 > 4-2 > 2-1 > 1
共4個動作,但是答案卻是3個。

麻煩了,謝謝。

版主回應
事實上應該可以縮減, 他每次會將整篇句子兩個空白縮成一個,也就是四個空白可以在一次操作縮成兩個。
接著我那邊的程式碼應該是打得有點累贅,但還是給你說的有差,就是當三個空白的時候,一次操作應該剩餘兩個空白,奇偶數的分別。
2012-10-07 15:14:15