【30.23%】【codeforces 552C】Vanya and Scales

时间:2023-03-09 14:26:43
【30.23%】【codeforces 552C】Vanya and Scales

time limit per test1 second

memory limit per test256 megabytes

inputstandard input

outputstandard output

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.

Input

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.

Output

Print word ‘YES’ if the item can be weighted and ‘NO’ if it cannot.

Examples

input

3 7

output

YES

input

100 99

output

YES

input

100 50

output

NO

Note

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.

【题目链接】:http://codeforces.com/contest/552/problem/C

【题解】



先将m转换成w进制;

如果最后w进制的每个位都为0或1,则直接输出YES;

对于w进制的m,如果其中的某一位存在w-1,则尝试将w-1变成-1,然后把后一位递增1;

如果某一位中存在2..w-2中的数则无解.

可以用样例的3 7来解释;

7 = 3^0 + 2*3^1;

因为2==3-1

则将2*3^1处理一下

变成(3-1)*3^1

就变成了1*3^2-1*3^1



7 = 3^0-3^1+3^2

这时每个数的系数都为1或-1,显然符合题意.

可以看到我们在进行这个转换的时候把第x位系数为w-1变成了-1,然后第x+1位的权值递增了1;即又添加了一个3^2;

那为什么系数为2..w-2的时候不能进行这样的转换?

比如w=4的时候系数为2

比如

2*4^3

这个时候会变成

(4-2)*4^3;

即4^4-2*4^3;

可以看到4^3的系数不会是-1.则不符合题意.因为每种砝码都只能选一次.移到左边后要用两次4^3.

当做技巧吧。不好想。



【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%I64d",&x) typedef pair<int,int> pii;
typedef pair<LL,LL> pll; const int MAXN = 100;
const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0); int w,m,cnt = 0;
int a[MAXN]; int main()
{
//freopen("F:\\rush.txt","r",stdin);
rei(w);rei(m);
while (m>0)
{
a[++cnt] = m%w;
m/=w;
}
rep1(i,1,cnt)
{
if (a[i] == w)
{
a[i+1]++;
a[i] = 0;
}
else
if (a[i]==w-1)
{
a[i] = -1;
a[i+1]++;
}
else
if (a[i] == 1 || a[i]==0)
continue;
else
{
puts("NO");
return 0;
}
}
puts("YES");
return 0;
}