您的位置:首页 > 其它

Codeforces Round #308 (Div. 2) C. Vanya and Scales(数制转换)

2015-06-19 11:07 239 查看
http://codeforces.com/contest/552/problem/C

要用质量为w0,w1,…,w100的砝码各1个称出重量m,砝码可以放在天平左边也可以放在右边。问是否可以称出,输出YES或NO。

即w进制的思想

问a1*w^0 + a2*w^1 + a3*w^2 +….+a100*w^100 = m 是否成立的问题

由于每个砝码最多只可以用一个 ,且可以放在两边,则系数a的取值只可能为-1,0,1,

我们考虑某位系数为-1的情况,则说明当前砝码跟物品放在一起,相当于给物品加上了这个砝码的重量。

类似于10进制,依次%W,判断其系数是否为-1,0,1,但是这里注意的一点是%w不可能出现-1,而是出现w-1的情况,当出现这种情况时如前面所说应该讲物品加上当前砝码的质量继续模拟即可

举个例子

1 + 3 - 9 -27 + 81 = 49

49

16 1

5 1

2 2

3 2

0 1

具体看代码:

#include<iostream>
#include<limits.h>
#include<queue>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define LL long long
using namespace std;

int main()
{
int n ,m;
cin>>n>>m;
if(n==3)//注意w为3的时候能称遍前n项和以内的所有数字,不加这个特判TLE
{
cout<<"YES"<<endl;
return 0;
}
while(m)
{
int x = m%n;
if(x==n-1) m = m/n + 1;
else if(x<=1) m/=n;
else
{
cout<<"NO"<<endl;
return 0;
}
}
cout<<"YES"<<endl;
return 0;
}


附上另一种直观的解法:

Basically, let’s try to solve:

c0 + c1*w^1 + c2*w^2 + … = m

Where each c0, c1, c2 are either -1, 0 or 1.

-1 means we used the weight on right, +1 means we used the weight on left and 0 means we did not use the weight at all.

=> c1*w^1 + c2*w^2 + … = m - c0

=> w(c1 + c2*w^1 + c3*w^2 + … ) = m - c0

=> c1 + c2*w^1 + c3*w^2 + … = (m - c0)/w

For such a solution to exist (m — c0) must be a multiple of w.

Let’s divide both sides by w and recursively solve if we can find such an m-c0 where c0 = -1 or 0 or 1

#include<iostream>
#include<limits.h>
#include<queue>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define LL long long
using namespace std;
bool solve(int ,int );
bool trySolve(int w, int m)
{
return m%w == 0 && solve(w, m/w);
}
bool solve(int w, int m)
{
return w == 2 || w == 3 || m == 1 || trySolve(w, m-1) || trySolve(w, m) || trySolve(w, m+1);
}

int main()
{
int n ,m;
cin>>n>>m;
if(solve(n,m)) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数制转换