Codeforces Round #647 (Div. 2) A题(贪心)

地址:http://codeforces.com/contest/1362/problem/A

题意:

给出a,b

a的操作:*2,*4  , *8  /2  /4  /8

问达到目标b最少需要多少步,达不到输出-1

解析:

贪心,如果a*x==b,那么这个x/(操作值)==步数。

这个步数,肯定是操作值越大,步数越小

所以我们从8开始,分别除8,4,2,直到x==1,就可以了

#include <cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll a,b;
        cin>>a>>b;
        if(a==b)
        {
            cout<<"0"<<endl;continue;
        }
        ll md;
        if(a>b&&a%b!=0)
        {
            cout<<"-1"<<endl;continue;
        }
        if(b>a&&b%a!=0)
        {
            cout<<"-1"<<endl;continue;
        }
        if(a>b)
        {
            md=a/b;
        }
        if(b>a)
        {
            md=b/a;
        }
        int ans=0;
        while(md&&md%8==0)
        {
            ans++;
            md=md/8;
        }
                while(md&&md%4==0)
        {
            ans++;
            md=md/4;
        }
                while(md&&md%2==0)
        {
            ans++;
            md=md/2;
        }
        if(md==1)
        cout<<ans<<endl;
        else
        cout<<"-1"<<endl;
    }
}
原文地址:https://www.cnblogs.com/liyexin/p/13051249.html