题解:P12322 [蓝桥杯 2024 国 Java C] 瞬移
Sparse_Table · · 题解
题目传送门
简单 bfs,队列里需要放
部分分
因为在枚举走多少步的时候,需要枚举
#include <bits/stdc++.h>
using namespace std;
int n, l, a[2005], vis[2005];
queue<pair<int, int>> q;
#define st first
#define nd second
#define mkp make_pair
int bfs() {
q.push({ 1, 0 });
while (!q.empty()) {
int x = q.front().st, d = q.front().nd;
q.pop();
if (x == l)
return d;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++) {
int nx = (x + a[i] + a[j] - 1) % l + 1;
if (!vis[nx]) {
vis[nx] = 1;
q.push(mkp(nx, d + 1));
}
}
}
return -1;
}
int main() {
cin >> n >> l;
for (int i = 1; i <= n; i++)
cin >> a[i];
cout << bfs();
return 0;
}
正解
既然
#include <bits/stdc++.h>
using namespace std;
int n, l, a[2005], vis[2005], can[2005];
queue<pair<int, int>> q;
#define st first
#define nd second
#define mkp make_pair
int bfs() {
vis[1] = 1;
q.push({ 1, 0 });
while (!q.empty()) {
int x = q.front().st, d = q.front().nd;
q.pop();
if (x == l)
return d;
for (int i = 1; i < l; i++)
if (can[i]) {
int nx = (x + i - 1) % l + 1;
if (!vis[nx]) {
vis[nx] = 1;
q.push(mkp(nx, d + 1));
}
}
}
return -1;
}
int main() {
cin >> n >> l;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++)
can[(a[i] + a[j]) % l] = 1;
cout << bfs();
return 0;
}
题解结束了,有问题欢迎私信!