原题:
Vanya has a scales for weighing loads and weights of massesw0, w1, w2, ..., w100 grams wherew is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with massm 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 massm 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.
题目大意:
给定两个数,w 和 m
有101个砝码,质量分别为 w 的 0 到 100 次方。有一个物体,质量为 m
问是否能在物体 m 放在天平上的情况下让天平平衡。
分析:
假设物体 m 放在天平左边,那么每个砝码只有放左边、放右边、不放三种情况,而砝码 w^i 放左边相当于在右边减去 w^i 的质量
所以我们其实就是要判断方程
m = a0*w^0 + a1*w^1 + a2*w^2 +...+ a100*w^100 ,其中 ai = -1 或 0 或 1
是否有解
我们发现这个方程的形式和 w 进制的数很类似,但是由于 -1 的存在,并不是标准合法的 w 进制数
但是我们发现在左盘放一个 w^i 的砝码,相当于在左盘放一个 w^(i+1) 的砝码,同时在右盘放 w-1 个 w^i 的砝码
所以我们可以把 ai 的取值变成 0 或 1 或 w-1
问题就转化为了判断 m 是否能表示成 w 进制数,且每一位的取值都是0或1或w-1
代码:
#include <iostream>
#include <cstdio>
using namespace std;
int n, m;
int main()
{
cin >> n >> m;
while (m)
{
if (m%n == 0) {}
else if (m%n == 1) {}
else if (m%n == n - 1) m++;
else {cout << "NO"; return 0;}
m /= n;
}
cout << "YES";
return 0;
}