Codeforces 552C Vanya and Scales(进制转换+思维)

题目链接:http://codeforces.com/problemset/problem/552/C

题目大意:
有101个砝码重量为w^0,w^1,....,w^100和一个重量为m的物体,问能否在天平两边放物品和砝码使其平衡。
解题思路:
将m化为w进制的数,接下来从低到高遍历没一位:
如果第i位是0那OK;
如果是1那就要把砝码wi放在天平另一边抵消;
如果是w-1那就要把砝码wi放到天平同一边,使其变为0并进位,这时第i+1位的权+1;
而如果是其他情况,那么肯定不能平衡了。

代码:

 1 #include<bits/stdc++.h>
 2 #define lc(a) (a<<1)
 3 #define rc(a) (a<<1|1)
 4 #define MID(a,b) ((a+b)>>1)
 5 #define fin(name)  freopen(name,"r",stdin)
 6 #define fout(name) freopen(name,"w",stdout)
 7 #define clr(arr,val) memset(arr,val,sizeof(arr))
 8 #define _for(i,start,end) for(int i=start;i<=end;i++)
 9 #define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
10 using namespace std;
11 typedef long long LL;
12 const int N=5e6+5;
13 const int INF=0x3f3f3f3f;
14 const double eps=1e-10;
15 
16 int a[105];
17 
18 int main(){
19     FAST_IO;
20     int w,m;
21     cin>>w>>m;
22     int cnt=0;
23     while(m){
24         a[cnt++]=m%w;
25         m/=w;
26     }
27     bool flag=true;
28     for(int i=0;i<105;i++){
29         if(a[i]>=w){
30             a[i+1]+=a[i]/w;
31             a[i]%=w;
32         }
33         if(a[i]!=0){
34             if(a[i]==w-1)
35                 a[i+1]++;
36             else if(a[i]==1)
37                 ;
38             else{
39                 flag=false;
40                 break;
41             }
42         }
43     }
44     if(flag)
45         cout<<"YES"<<endl;
46     else
47         cout<<"NO"<<endl;
48     return 0;
49 }

猜你喜欢

转载自www.cnblogs.com/fu3638/p/9131476.html