题意:可以把n边为n+1,n-1,n*2问从n到k的最少变化次数。
坑:标题写了。有点不会写bfs了。。。
ac代码
#define _CRT_SECURE_NO_WARNINGS #include<cstring> #include<cctype> #include<cstdlib> #include<cmath> #include<cstdio> #include<string> #include<stack> #include<ctime> #include<list> #include<set> #include<map> #include<queue> #include<vector> #include<sstream> #include<iostream> #include<functional> #include<algorithm> #include<memory.h> //#define INF 0x3f3f3f3f #define eps 1e-6 #define pi acos(-1.0) #define e exp(1.0) #define rep(i,t,n) for(int i =(t);i<=(n);++i) #define per(i,n,t) for(int i =(n);i>=(t);--i) #define mp make_pair #define pb push_back #define mmm(a,b) memset(a,b,sizeof(a)) //std::ios::sync_with_stdio(false); using namespace std; typedef long long ll; typedef unsigned long long ull; void smain(); #define ONLINE_JUDGE int main() { ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); long _begin_time = clock(); #endif smain(); #ifndef ONLINE_JUDGE long _end_time = clock(); printf("time = %ld ms.", _end_time - _begin_time); #endif return 0; } const int maxn = 1e5 + 5; int vis[maxn]; struct node { int x, t; node(int n = 0, int k = 0) :x(n), t(k) {} }; int n, k; bool check(int x) { if ( x > 1e5 || x < 0|| vis[x])return 0; else return 1; } void Run() { queue<node> Q; Q.push(node(n,0)); vis[n] = 1; while (!Q.empty()) { node now = Q.front(); Q.pop(); if (now.x == k) { cout << now.t; break; } if (check(now.x + 1))Q.push(node(now.x + 1, now.t + 1)),vis[now.x + 1] = 1; if (check(now.x - 1))Q.push(node(now.x - 1, now.t + 1)), vis[now.x - 1] = 1; if (check(now.x * 2))Q.push(node(now.x * 2, now.t + 1)), vis[now.x * 2] = 1; } } void smain() { cin >> n >> k; Run(); }