CF 552C 進位制轉換

life4711發表於2015-06-27

http://codeforces.com/problemset/problem/552/C

C. Vanya and Scales
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard 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 ≤ 1091 ≤ 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.

Sample test(s)
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.


/**
CF 552C 進位制轉換
題目大意:給定一個天平,砝碼的重量為w的0~100次冪,每種砝碼只有一個,砝碼可以放在左盤或者右盤。給定物品的重量m,問是否有一種方案讓天平兩端平衡
解題思路:把m化為w進位制,改進位制數只能有0,1或者w-1,若為w-1那麼相當於在物品所放的盤裡加一個砝碼,然後在另一盤加上w倍的砝碼即可。直接w進位制數當前位
          清0,將下一位+1即可。最後看w進位制數是否正好是一個01串即可
*/
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <iostream>
using namespace std;
int bit[40],n,m;
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        int k=0;
        memset(bit,0,sizeof(bit));
        while(m)
        {
            bit[k++]=m%n;
            m/=n;
        }
        int flag=1;
        for(int i=0;i<k;i++)
        {
            if(bit[i]>=n)
            {
                bit[i]-=n;
                bit[i+1]++;
            }
            if(bit[i]==n-1)
            {
                bit[i]=0;
                bit[i+1]++;
            }
            else if(bit[i]>1)
            {
                flag=0;
                break;
            }
        }
        if(flag==0)
            puts("NO");
        else
            puts("YES");
    }
    return 0;
}


相關文章