Codeforces Round #547 (Div. 3)1141A

n能否乘2或3任意次变为m n,m<5e8
暴力最快 dfs bfs最慢还不好写
方法1 暴力

int n,m,cnt=0;
	cin>>n>>m;
	if(n==m)
	{
		cout<<0<<endl;
		return 0;
	}
	if(m%n!=0)
	{
		cout<<-1<<endl;
		return 0;
	}
	int ans=m/n;//只剩2,3因子
	//最坏 n=1 m=5e8 ans=5e8 只剩2,3因子 5e8最坏多少次2得到 1000*1000*500
	//10c+10c+10c 最大30次
	while(ans%2==0)
	{
		ans=ans/2;
		cnt++;
	 }
	while(ans%3==0)
	{
		ans=ans/3;
		cnt++;
	}
	//n=15 m=150 m有n因子 ans=10=2*5 ans=5;不为1 不能达到
	if(ans!=1)
		cout<<-1<<endl;
	else
		cout<<cnt<<endl;//保证只有2,3因子 

方法2 dfs最好用全局变量 dfs最大30次相当于暴力
1-5e8

int n,m,ans=INF;
void dfs(int n,int cnt)//乘2,3次数 
{
	//n=42 m=42 m==n n达到m的特例 
	if(n==m)
	{
		ans=min(ans,cnt);//乘2,3次数都不同 哪种情况更优 
		return;
	}
	if(n>5e8)
		return;//24 75 m无n因子 
	dfs(n*2,cnt+1);
	dfs(n*3,cnt+1);
}
int main()
{
	IO;
	
	cin>>n>>m;
	dfs(n,0);//n开始乘多少次2,3变为m 
	if(ans==INF)
		cout<<-1<<endl;//只要n达不到m ans永远不会更新 
	else
		cout<<ans<<endl;//最少2,3数量 
	return 0;
} 

方法3 bfs

#include<iostream>
#include<cstdio>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.precision(0);
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

const ll inf=0x3f3f3f3f3f3f3f3f;
const int INF=0x3f3f3f3f; 
const ll mod=1e9+7;
const int maxn=2e5+5;
ll gcd(ll a,ll b){return b!=0?gcd(b,a%b):a;}

int main()
{
	IO;
	//bfs认为*2 *3同时进行
	int n,m;
	cin>>n>>m;
	queue<pii> q;//存 当前值 次数
	q.push(mp(n,0));
	while(!q.empty())
	{
		pii p=q.front();
		q.pop();
		if(p.first==m)
			return cout<<p.second<<endl,0;
		if(p.first*2<=m)
			q.push(mp(p.first*2,p.second+1));
		if(p.first*3<=m)
			q.push(mp(p.first*3,p.second+1));
	 }
	 if(q.empty())
	 	cout<<-1<<endl;//越过m 弹栈就完事了 
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_40423146/article/details/88921118