POJ3210:Coins

点击打开题目链接


Coins

Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 6488   Accepted: 4236

Description

Snoopy has three coins. One day he tossed them on a table then and tried to flip some of them so that they had either all heads or all tails facing up. After several attempts, he found that regardless of the initial configuration of the coins, he could always achieve the goal by doing exactly two flippings, under the condition that only one coin could be flipped each time and a coin could be flipped more than once. He also noticed that he could never succeed with less than two flippings.

Snoopy then wondered, if he had n coins, was there a minimum number x such that he could do exactly x flippings to satisfy his requirements?

Input

The input contains multiple test cases. Each test case consists of a single positive integer n (n < 10,000) on a separate line. A zero indicates the end of input and should not be processed.

Output

For each test case output a single line containing your answer without leading or trailing spaces. If the answer does not exist, output “No Solution!

Sample Input

2
3
0

Sample Output

No Solution!
2

Source

POJ Monthly--2007.04.01, Snoopy


=====================================题目大意=====================================


求解对于N枚硬币是否存在一个最小的正整数X使得无论这N枚硬币初始状态如何总可以通过恰好X次的翻转操作使得它们全部正面朝上

或全部反面朝上。


=====================================算法分析=====================================


设硬币总数为N,初始时正面朝上的硬币数为N(+),反面朝上的硬币数为N(-)。

将翻转操作分“翻转每枚硬币最多一次使它们全部正面向上或全部反面向上”和“多余翻转”两部分考虑。

显然前者的翻转操作次数为为N(+)或N(-),而后者的翻转操作次数相应为N-N(+)或N-N(-)。

X满足题意的关键是“多余翻转”的次数必须是非负偶数,也即对于任意N(+)和N(-)的组合情况总有“X-N(+)为非负偶数或者

X-N(-)为非负偶数”。

若N为偶数,则当N(+)与N(-)都为偶数时X必须为偶数,当N(+)与N(-)都为奇数时X必须为奇数,综上两种情况,X不可能存在。

若N为奇数,令N1和N2分别为N(+)和N(-)中的奇数和偶数,那么X可以是不小于N1的奇数(最小值即N)也可以是不小于N2的偶数(最

小值即N-1)。

综上两种情况,X应取N-1。


=======================================代码=======================================




#include<stdio.h>

int N;

int main()
{
    while(scanf("%d",&N)==1&&N)
    {
		if(N&1) printf("%d\n",N-1);
		else printf("No Solution!\n"); 
    }
    return 0;
}

你可能感兴趣的:(模拟,基本算法)