B. Getting Zero

2 篇文章 0 订阅
本文介绍了一个用C++实现的BFS算法,用于求解模运算中从一个整数到模的最短操作数问题,涉及边权和邻接列表的构建。
摘要由CSDN通过智能技术生成

这题可以使用bfs的做法,特记录在此。

x点到mod的操作数可以视为其最短路。于是可用宽搜从1到mod建图。

有边权为(x+1)%mod  和(2*x)%mod 两种边权。

所以每次求数x到mod的最下操作数变为到mod这个顶点的最小边数。

#include "bits/stdc++.h"
using namespace std;

#define int long long 
#define endl '\n'
#define IOS ios::sync_with_stdio(0),cin.tie(0);
#define all(x) x.begin(),x.end()
#define pi pair<int,int> 
#define vi vector<int>
#define si set<int> 
#define mi map<int,int>
#define mc map<char,int>
#define YES cout<<"Yes"<<endl;
#define NO  cout<<"No"<<endl;
#define pb(x) push_back(x);

template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
const int mod=32768;
int ans[mod];
typedef struct node{
	int x,step;
}NODE;
queue<NODE>q;
int st[mod];
vector<int> v[mod];
void bfs()
{
	NODE tmp={0,0},t1;
	q.push(tmp);
	st[0]=1;
	
	while(q.size()){
		t1=q.front();
		q.pop();
		for (auto i:v[t1.x] ){
			if(!st[i]){
				st[i]=1;
				ans[i]=ans[t1.x]+1;
				tmp={i,ans[i]};
				q.push(tmp);
			}
		}
	}
	
	
}

void solve()
{

	for (int i=1;i<mod;i++){
		v[(i+1)%mod].push_back(i);
		v[(2*i)%mod].push_back(i);
	}
	bfs();
	int n;
	cin>>n;
	for (int i=1;i<=n;i++){
		int x;
		cin>>x;
		cout<<ans[x]<<" ";
	}
    cout<<endl;
	
}

signed main()
{
	IOS
	int t;
t=1;//cin>>t;
	while(t--){
		solve();
	}
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值