題目描述:
A weird clock marked from 0 to 59 has only a minute hand. It won't move until a special coin is thrown into its box. There are different kinds of coins as your options. However once you make your choice, you cannot use any other kind. There are infinite number of coins of each kind, each marked with a number d ( 0 <= 1000 ), meaning that this coin will make the minute hand move d times clockwise the current time. For example, if the current time is 45, and d = 2. Then the minute hand will move clockwise 90 minutes and will be pointing to 15.
Now you are given the initial time s ( 0 <= s <= 59 ) and the coin's type d. Write a program to find the minimum number of d-coins needed to turn the minute hand back to 0.
Input
There are several tests. Each test occupies a line containing two positive integers s and d.
The input is finished by a line containing 0 0.
Output
For each test print in a single line the minimum number of coins needed. If it is impossible to turn the hand back to 0, output "Impossible".
Sample Input
30 10 0
Sample Output
1
解題思路:首先在學習別人的解題報告時學會了判斷是否到資料的尾0 0時的簡便方法;該題不能使用窮舉方法一直列舉下去,這樣不能判斷impossible,只會陷入死迴圈,所以簡單的方法是利用一個數組記錄每次分針指向的數,當之後再指向是就是迴圈了就不能指到0了就是impossible;還有一個更巧妙的方法 是利用60的因子分解,60=2*2*3*5,每次now = ((d + 1) * now) % 60,如果可以,那麼最多2次就可以到達0,否則永遠到達不了。
法二:
#include <iostream>#include<stdio.h>#include<stdlib.h>using namespace std;int main(){ int now,d,i,j,n = 0; int num[60] = {0}; int answer[60] = {0}; while((scanf("%d %d",&now,&d) == 2)&&(now || d)) { if(now == 0) { answer[n] = 0; continue; } if(d == 0) { answer[n] = -1; continue; } for(i = 1;;i++) { j = ((i * d)*now+now)%60; if(j == 0) { answer[n] = i; break; if(num[j]) { answer[n] = -1; break; } else num[j] = 1; } } n++; } for(i = 0;i < n;i++) { if(answer[i] == -1) printf("Impossible!\n"); else printf("%d\n",answer[i]); } return 0;}
法二:
#include <stdio.h>int main(){ int d, tmp; int num; while(scanf("%d%d", &tmp, &d) == 2 && (tmp || d)) { if(tmp == 0) { printf("0\n"); continue; } if(d == 0) { printf("Impossible\n"); continue; } for(num = 1; num <= 2; num++) { tmp = ((d + 1) * tmp) % 60; if(tmp == 0) break; } if(tmp == 0) printf("%d\n", num); else printf("Impossible\n"); } return 0;}