Codeforces 552C Vanya and Scales

本文探讨了一个有趣的称重问题:如何使用一系列特定质量的砝码来判断能否平衡地称出给定质量的物品。通过将物品质量转换为特定基数表示,并逐位调整,最终确定是否能实现平衡称重。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Sample test(s)
Input
3 7
Output
YES
Input
100 99
Output
YES
Input
100 50
Output
NO

解题思路:将m化成w进制表示,我们要想方设法对m的w进制表示中的每一位进行加1操作使得它的w进制表示为0,1串的形式,这样我们便是能够用砝码来表示的,每种砝码只能用一次。
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <algorithm>
#include <functional>
using namespace std;
int bit[110];

int main() {

    int w, m;
    int bcnt = 0;
    scanf("%d %d", &w, &m);
    bool ok = true;
    while(m) {
        bit[bcnt++] = m % w;
        m /= w;
    }
    for(int i = 0; i < bcnt; ++i) {
        if(bit[i] >= w) {
            bit[i] -= w;
            bit[i+1]++;
        }
        if(bit[i] <= 1) {
            continue;
        }
        else if(bit[i] == w - 1) {
            bit[i] = 0;
            bit[i+1]++;
        } else {
            ok = false;
        }
    }
    if(ok) printf("YES\n");
    else printf("NO\n");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值