Codeforces Round #308 (Div. 2) C.Vanya and Scales

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.

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.

题意:

给你w和m,问你m能否通过加减w的n次方来使m=0,w的0-100次方分别能用一次。

分析:

开始想dp或者暴力,后来发现其实m能否减去或加上某个w实际上是固定的。先取w的n次方,令w的n次方大于m且w的n-1次方小于等于m。如果m加上此时w的n-1次方的值后,后续的w的1-n-2次方之和大于m,则允许减,否则不允许减,而是要增大m,使m达到w的n次方。增大过程同样符合此条件,最早得到答案。
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define INF 0x3f3f3f3f
const int N=215;
const int mod=1e9+7;

int g[N][N];

int main() {
    int w,m;
    while (cin>>w>>m) {
        if (w>m) {
            if (w-m==1||m==1) {
                cout<<"YES\n";
            } else cout<<"NO\n";
            continue;
        }
        long long t=1;
        while (m>=t) {
            t*=w;
        }
        while (t>=1) {
            if ((long long)m*(w-1)>t-1) {
                long long flag=t;
                flag/=w;
                while (m<t&&flag) {
                    if ((m+flag-t)*(w-1)<=flag-1) {
                        m+=flag;
                    }
                    flag/=w;
                }
                m-=t;
                t=flag;
            } else {
                if (m>=t) {
                    m-=t;
                } else {
                    t/=w;
                }
            }
        }
        if (m==0) {
            cout<<"YES\n";
        } else cout<<"NO\n";
    }
    return 0;
}


你可能感兴趣的:(Codeforces Round #308 (Div. 2) C.Vanya and Scales)