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

题目链接:

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

题意:

给你100个砝码,第i个砝码质量是w^i,然后问你能不能在有m的情况下,左边和右边都放砝码,使得这个天平平衡

题解:

dfs直接暴力
对于这个砝码来说,只有3种选择,放左边,不放,放右边
由于2和3直接输出yes,所以答案也就没多少了

正解:m的w进制, 从低位到高位 模拟。。 每一位只能是0,1,w-1,因为每种位置的砝码只有一个 所以 在i位上是1 就是要在另一端天平上 放一个w^i的砝码与其抵消 对于w-1 就是相当于进到高一位上去

dfs~390ms maxn开到4e9 。。 1e9会WA 1e10会TLE 唉….

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
ll maxn = 4e9;
ll w,m;
bool f;

void dfs(ll b,ll c){
    if(c == m){
        f = 1;
        return ;
    }
    if(f) return ;

    if(abs(b) <= maxn){
        dfs(b*w,c+b);
        dfs(b*w,c-b);
        dfs(b*w,c);
    }
}

int main(){
    f = 0;
    cin >> w >> m;
    // cout << (ll) (w*m) << endl;
    if(w<=3){
        puts("YES");
        return 0;
    }
    dfs(1,0);

    if(f) puts("YES");
    else puts("NO");

    return 0;
}

正解代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;

int main(){
    int w = read(), m = read();
    if(m <= 3) {
        puts("YES");
        return 0;
    }

    while(m){
        int yu = m % w;
        if(yu <= 1)
            m /= w;
        else if(yu == w-1)
            m = m/w+1;
        else{
            puts("NO");
            return 0;
        }
    }
    puts("YES");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值