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
解题思路:将m化成w进制表示,我们要想方设法对m的w进制表示中的每一位进行加1操作使得它的w进制表示为0,1串的形式,这样我们便是能够用砝码来表示的,每种砝码只能用一次。
#include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include <deque> #include <queue> #include <stack> #include <map> #include <set> #include <utility> #include <algorithm> #include <functional> using namespace std; int bit[110]; int main() { int w, m; int bcnt = 0; scanf("%d %d", &w, &m); bool ok = true; while(m) { bit[bcnt++] = m % w; m /= w; } for(int i = 0; i < bcnt; ++i) { if(bit[i] >= w) { bit[i] -= w; bit[i+1]++; } if(bit[i] <= 1) { continue; } else if(bit[i] == w - 1) { bit[i] = 0; bit[i+1]++; } else { ok = false; } } if(ok) printf("YES\n"); else printf("NO\n"); return 0; }