简单 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;
}题解结束了,有问题欢迎私信!