-
-
输入格式
共一行,包含两个整数N和K。
输出格式
输出一个整数,表示抓到牛所花费的最少时间。
数据范围
0≤N,K≤1e5
输入样例:
5 17
输出样例:
4
分析: 注意适当剪枝!不然会超内存
法一:使用pair——40 ms
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N = 1e7 + 10;
typedef pair<int, int>pii;
int st, ed;
bool vis[N];
void bfs() {
queue<pii>q;
q.push(make_pair(st, 0));//起始位置和step;
vis[st] = true;
while (q.size()) {
int now = q.front().first;
int step = q.front().second;
q.pop();
if (now == ed) {
cout << step << endl;
return;
}
if (now + 1 <= ed && !vis[now+1]) {
vis[now+1] = true;
q.push({ now+1,step + 1 });
}
if (now-1>=0&& !vis[now-1]) {
vis[now-1] = true;
q.push({ now-1,step + 1 });
}
if (now <= ed &&!vis[now*2]) {
vis[now*2] = true;
q.push({ now*2,step + 1 });
}
}
cout << "no" << endl;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> st >> ed;
bfs();
return 0;
}
法二:开dis数组存放步数——105ms,比pair慢
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N=2e5+10;
int n,k,dist[N];
int bfs()
{
memset(dist,-1,sizeof dist);
queue<int> q;
q.push(n);
dist[n]=0;
while(q.size())
{
int t=q.front();
q.pop();
if(t==k) return dist[k];
if(t+1<N&&dist[t+1]==-1)
{
dist[t+1]=dist[t]+1;
q.push(t+1);
}
if(t-1>=0&&dist[t-1]==-1)
{
dist[t-1]=dist[t]+1;
q.push(t-1);
}
if(2*t<N&&dist[2*t]==-1)
{
dist[2*t]=dist[t]+1;
q.push(2*t);
}
}
return -1;
}
int main()
{
cin>>n>>k;
cout<<bfs()<<endl;
return 0;
}
这种写法很方便
while (q.size()) {
int now = q.front().first;
int step = q.front().second;
q.pop();