Codeforces 552.C Vanya and Scales

来源:互联网 发布:嫁给老男人 知乎 编辑:程序博客网 时间:2024/06/05 06:23

    此题是一道思维转化题,给出AC代码及理解分析。

    见题目:

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 wherew 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的0次方、w一次方……w n次方的砝码称出所给物体的重量,每个砝码都是唯一的不可重复使用。天平两侧都可放置砝码,以例一分析:要想称出7,需在7的那一侧放一个3,在天平另一侧放一个9和1,即可称出7的重量。

    分析:该题可转化为一道w进制相关的题,模拟一下天平可得到如下式子:a0*w^0+a1*w^1+……+an*w^n=m,其中的a0-an均为0,1,-1(即该天平放在右侧),若满足条件即可判断。于是可以对式子进行逐次除以w后取余即可依次得到a0、a1等的值,由于取模不可能得到负值所以取模后的结果只能为0,1,w-1,这一点理解较困难,举例:若w=5,天平左侧放物体,右侧放砝码,若左侧放了一个5的砝码,那么整理式子至式子一端为m时,a1应为-1,但不满足运算法则,所以5的高次即5的平方次a2需要降一位给低位,那么a1的即为w-1=4,反过来求取a2的时候需要加一后取余。这一点相当于先将左侧的砝码拿走后又将左侧砝码加上。理解这一点不难写出代码。重复过程直至被除数为0或者存在不符合情况的余数输出NO即可。以上为解题分析。

    测试中可以发现w等于1、2、3此题中可以构成任何数。

    见AC代码:

#include <cstdio>int main(){int w,m;while(scanf("%d%d",&w,&m)!=EOF){if(w<=3){puts("YES");//2 3 在此题中可以构成任何数字   continue;}int flag=1;while(m){int x=m%w;if(x<=1)m/=w;else if(x==w-1) m=m/w+1;//向高位借了一位  所有除的时候需要加一  else{puts("NO");flag=0;break;}}if(flag)puts("YES");}return 0;}

    现在还是井底之蛙,唯有多做多练才能增长能力。

    特记下,以备后日回顾。

0 0
原创粉丝点击