2024-2
1)因为我当时最后一行用的cin依次输入,在devc上就需要按ctrl+z才可以停止输入,这样就不行,所以一直没有输出。所以直接改成getline读入字符串再把数字切割出来的形式,但是又忽略了上一行用的cin,所以要加cin.ignore()去忽略换行符
2)之前一直知道bfs要加点,但是还是很混乱,因为没有注意到到底是加的结点的值还是结点的位置,其实是结点的值,或者你肯定要统一,就不会混乱了,以后都加结点本身。
3)题目在给出根节点的时候给出了-1,不要把-1当结点加入树中,可以直接忽略,然后定义一个根节点
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
#include <cctype>
using namespace std;
const int N = 10000;
int h[N], e[N], ne[N], type[N], idx, root;
set<int> info;
bool st[N];
void add(int x, int y, int z)
{
if(y == -1) root = x;
type[idx] = z, e[idx] = x, ne[idx] = h[y], h[y] = idx;
// cout << e[idx] << endl;
idx ++;
}
void bfs()
{
queue<int> q, res;
// cout << root << endl;
q.push(root);
while(q.size())
{
auto t = q.front();
// cout << t << endl;
q.pop();
for(int i = h[t]; i != -1; i = ne[i])
{
if(info.find(e[i]) != info.end())
{
if(!st[e[i]]) res.push(e[i]), st[e[i]] = true;
if(!st[t]) res.push(t), st[t] = true;
}
q.push(e[i]);
// cout << e[i] << endl;
}
}
// cout << res.size() << endl;
while(res.size())
{
auto t = res.front();
res.pop();
for(int i = h[t]; i != -1; i = ne[i])
{
if(info.find(e[i]) == info.end() && type[i] == 0) cout << e[i] << " ";
}
}
}
int main()
{
memset(h, -1, sizeof h);
int n;
cin >> n;
while(n --)
{
int x, y, z;
cin >> x >> y >> z;
add(x, y, z);
}
// cout << h[-1] << endl;
// for(int i = h[1]; i != -1; i = ne[i])
// cout << e[i] << endl;
// int m;
// while(cin >> m)
// {
// info.insert(m);
// }
cin.ignore();
string s;
getline(cin, s);
// cout << s << endl;
for(int i = 0; i < s.size(); i ++)
{
if(isdigit(s[i])){
int x = 0, j = i;
while(j < s.size() && isdigit(s[j])) x = x * 10 + s[j ++] - '0';
info.insert(x);
}
}
// cout << info.size() << endl;
bfs();
return 0;
}
样例:
6
1 -1 1
2 1 0
3 1 0
4 1 0
5 3 0
6 3 1
2 3
输出:
5 4