为什么用数组 58 结构体 AC?
查看原帖
为什么用数组 58 结构体 AC?
946696
mlemtion楼主2024/6/8 19:48

测评记录 代码:

#include <bits/stdc++.h>
using namespace std;
int n, a, b, t, k[300], times[300];
queue<int> q;
int main() {
	ios::sync_with_stdio(0);
	cin >> n >> a >> b;
	for (int i = 1; i <= n; i++)cin >> k[i];
	memset(times,0x3f,sizeof(times));
	q.push(a);
	times[a]=0;
	while(!q.empty()){
		t=q.front();
		q.pop();
		if(t==b){
			cout<<times[b];
			return 0;
		}
		if(t+k[t]<=n&&times[t+k[t]]==0x3f3f3f3f){
			q.push(t+k[t]);
			times[t+k[t]]=times[t]+1;
		}
		if(k[t]!=0&&t-k[t]>=1&&times[t+k[t]]==0x3f3f3f3f){
			q.push(t-k[t]);
			times[t-k[t]]=times[t]+1;
		}
	}
	cout<<-1;
	return 0;
}

下面是用结构体AC的代码:

#include <bits/stdc++.h>
using namespace std;
struct Node{
	int f,c;
}node;
int n, a, b, t, k[300];
bool vis[300];
int main() {
	ios::sync_with_stdio(0);
	cin >> n >> a >> b;
	for (int i = 1; i <= n; i++)cin >> k[i];
	queue<Node> q;
	q.push({a,0});
	vis[a]=1;
	while(!q.empty()){
		node=q.front();
		t=node.f;
		q.pop();
		if(t==b){
			cout<<node.c;
			return 0;
		}
		if(t+k[t]>=1&&t+k[t]<=n&&vis[t+k[t]]==0){
			q.push({t+k[t],node.c+1});
			vis[t+k[t]]=1;
		}
		if(t-k[t]>=1&&t-k[t]<=n&&vis[t-k[t]]==0){
			q.push({t-k[t],node.c+1});
			vis[t-k[t]]=1;
		}
	}
	cout<<-1;
	return 0;
}
2024/6/8 19:48
加载中...