gpt4 book ai didi

C++ STL 广度优先搜索

转载 作者:行者123 更新时间:2023-11-28 05:29:06 25 4
gpt4 key购买 nike

#include <queue>
#include <vector>
#include <iostream>
using namespace std;


int main() {
int x;
cin >> x;
for(int tt=0;tt<x;tt++)
{
//cout << "HI" << endl;
int n, m;
cin >> n >> m;
vector< vector<int> > g(n);
for(long j =0; j< m;j++)
{
int u , v;
cin >> u >> v;

g[u-1].push_back(v-1);
g[v-1].push_back(u-1);

}

int s;
cin >> s;

vector<int> out(n,-1);
vector<int> visited(n,0);
int value = 0;
queue<int> q;
q.push(s-1);
q.push(-1);
visited[s-1] =1;
int flag =0;
while(!q.empty())
{
int v = q.front();
out[v] = value;
q.pop();
if(v == -1)
{
value += 6;
}
else{
for(vector<int>::iterator it = g[v].begin(); it != g[v].end();it++)
{
if(visited[*it] == 0)
{
q.push(*it);
visited[*it] =1;
}
}
}

}
//cout << "hello" << endl;
for(int k =0; k<n; k++)
{
if(k!= s-1)
{
cout << out[k] << " ";
}
}
cout << endl;
//cout << "yo";
}
//cout << "you";
return 0;
}

如果起始节点只有一级邻居,则此代码运行良好。为了使其适用于所有情况,当我更改时

if(v == -1)
{
value += 6;
}

if(v == -1)
{
value += 6;
if(!q.empty())
q.push(-1);
}

它现在甚至不适用于所有测试用例。然后程序中止,来自 hacker rank 的错误信息是* ‘解决方案’中的错误:双重释放或损坏(输出):0x00000000009e5cf0 *

我不明白为什么会这样。为什么我在处理队列的时候for循环有问题。

hackerrank 问题的链接。

https://www.hackerrank.com/challenges/bfsshortreach

最佳答案

你需要

  1. 摆脱 value ,它不是必需的。
  2. vector 越界访问就在那里。什么是 out[-1] ?
  3. 适当的缩进
  4. Bfs 总是明智地访问级别。您不需要通过在队列中推送负值来维护它。

正确的代码是:

#include <queue>
#include <vector>
#include <iostream>
using namespace std;


int main() {
int x,n, m,u , v;
cin >> x;
for(int tt=0;tt<x;tt++){
cin >> n >> m;
vector< vector<int> > g(n);
for(long j =0; j< m;j++){
cin >> u >> v;
g[u-1].push_back(v-1);
g[v-1].push_back(u-1);
}

int s;
cin >> s;

vector<int> out(n,-1);
vector<bool> visited(n,0);
queue< int > q;
q.push(s-1);
visited[s-1] =1;
out[s-1]=0;

while(!q.empty()){
int v = q.front(); q.pop();

for(vector<int>::iterator it = g[v].begin(); it != g[v].end();it++){
if(visited[*it] == 0){
q.push(*it);
visited[*it] =1;
out[*it]=out[v]+6;
}
}

}
for(int k =0; k<n; k++){
if(k!= s-1){
cout << out[k] << " ";
}
}
cout << endl;
}
return 0;
}

关于C++ STL 广度优先搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39915167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com