Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2(exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.
The first line contains two integers w, m (2 ≤ w ≤ 109, 1 ≤ m ≤ 109) — the number defining the masses of the weights and the mass of the item.
Print word 'YES' if the item can be weighted and 'NO' if it cannot.
3 7
YES
100 99
YES
100 50
NO
Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1.
Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.
Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input.
解体思路:开始想到用背包,但砝码的质量太大了,于是想dfs,然而超时.看了人家写的题解,思维太巧妙了.因为砝码的是w的次方,那么可以称重物m,那么m就是w的倍数,或者m+1是w的倍数,或m-1是w的倍数。不断将m分解,会发现得到的新的m仍然符合上述条件。否则天平两边不可能平衡。
代码如下:
#include<stdio.h>
#define LL long long
int main(){
int w,m;
while(scanf("%d%d",&w,&m)!=EOF){
while(m){
if((m-1)%w==0) m--;
else if((m+1)%w==0) m++;
else if(m%w){
printf("NO\n");
break;
}
m/=w;
}
if(!m) printf("YES\n");
}
return 0;
}