POJ 3210 : Coins
POJ 3210 : Coins
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 7001 Accepted: 4616
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
題意我認為非常難理解,意思是n個硬幣,不管是怎麽擺的(正面或是反面),是否能找到一個最小值x。使得這n個硬幣。通過x次翻轉,必能到達全正或是全反的狀態。能。則輸出x的值。
不能,則輸出“No Solution!”
分情況討論:
如果n是一個偶數:
如果向上的數量為偶數,則向下的數量也一定為偶數,所以這個最小值x也一定是偶數。
如果向上的數量是奇數。則向下的數量也是奇數,這個最小值x一定得是奇數。
此時。
得到的x在兩種情況中互相矛盾,所以偶數的話,要輸出“No Solution!”
如果n是一個奇數:
事實上n是一個奇數的話,僅僅有一種情況了,向上的數量是m,向下的數量是n-m。兩者一定一個奇數。一個偶數。此時向上即向下,向下即向上。
此時會發現偶數次翻轉就可以完畢任務,僅僅需將狀態不同的兩種硬幣中,為偶數的數量的那一堆翻轉就可以,此時兩堆硬幣已經達到了同上或是同下。這時,多出來的反轉次數,僅僅需對一個硬幣來回翻轉,由於是偶數次,所以不影響最後狀態了。
那麽這個x最小是多少?
如果n個硬幣。1個向上,n-1個向下。依據上面所述,這時須要n-1次翻轉。這時是滿足全部情況的最小值了。
代碼:
#include<iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
if(n==0)
break;
if(n%2)
{
cout<<n-1<<endl;
}
else
{
cout<<"No Solution!"<<endl;
}
}
return 0;
}
POJ 3210 : Coins