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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章