Coins POJ - 3210

探讨了给定n个硬币时,如何通过最少次数的翻转使所有硬币朝向一致的问题。对于不同数量的硬币,解决方案各异,涉及算法分析与实现。

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

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
  题意比较难理解。。。。给定n个硬币,无论硬币怎么放置,你都能通过x次翻转(每次仅能翻转一次),让硬币全正或者全反面。
思路:当n==2是,桌面为一正一反,应该翻奇数次,若全为正全为反,应该翻偶数次

                     由此可推,当n为偶数时,正面为奇数,反面为奇数,一定要翻奇数次才能保证全正或者全反。正面为偶数,一定要翻偶数次才符合题意。可知n若为偶数,一定不可能翻出要求的情况。

  当n为奇数时,若有1个与其他面不同,假设翻转仅一次,对其他条件不符合(如果有两个面与其他不同),所以应该翻n-1次,可以达到无论初始怎么放置,都可以达到要求。


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
int main()
{
    while(~scanf("%d",&n),n)
    {
        if(n%2==0)
            printf("No Solution!\n");
        else
        {
            printf("%d\n",--n);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值