跳到正文

个人记录

ufgj

SEF_711约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年5月20日
更新
2026年5月20日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;

const int kN = 2e6 + 5;
int ex;
bool vis[kN];
struct node {
    int x, step;
};
int bfs(int sx) {
    queue<node> q;
    memset(vis, 0, sizeof vis);
    q.push({sx, 1});
    vis[sx] = 1;
    while(q.empty() == 0) {
        node cur = q.front();
        q.pop();
        if(cur.x == ex) {
            return cur.step - 1;
        }
        for(int i = 0; i < 2; i ++) {
            int nx;
            if(i == 1) {
                nx = cur.x + cur.step + 1;
            }
            else {
                nx = cur.x - 1;
            }
            if(vis[nx] == 1) {
                continue;
            }
            vis[nx] = 1;
            q.push({nx, cur.step + 1});
        }
    }
    return -1;
}
void work() {
    cin >> ex;
    cout << bfs(0) << "\n";
}
int main() {
    int t;
    cin >> t;
    while(t --) {
        work();
    }
    return 0;
}
原文