蒟蒻只会bfs,求助,WA#1
查看原帖
蒟蒻只会bfs,求助,WA#1
826932
xs196619楼主2023/7/25 20:50

bfs1用来求深度和宽度,bfs2是用来求两点之间的距离。提交后WA#1,显示的是距离错了,正确答案是4,但是显示3 。

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int n, x, y, u, v, h[105], e[210], ne[210], idx, q[105], ans=0,d[105],deep=1,width=1,s[110];
void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void bfs1()
{
    int hh = 0, tt = 0;
    q[0] = 1;
    memset(d, 0, sizeof d);
    d[1] = 1;
    s[1]++;
    while (hh <= tt)
    {
        int t = q[hh++];
        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (d[j] == 0)
            {
                d[j] = d[t] + 1;
                s[d[j]]++;
                deep = max(d[j], deep);
                q[++tt] = j;
            }
        }
    }
    for (int i = 1; i <= n; i++)
    {
        width = max(width, s[i]);
    }
}
void bfs2(int u)
{
    int hh = 0, tt = 0;
    q[0] = u;
    memset(d, -1, sizeof d);
    d[u] = 0;
    while (hh <= tt)
    {
        int t = q[hh++];
        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (d[j] == -1)
            {
                if (j < t)//如果邻接节点比当前队头节点小,说明是往上走,距离=队头节点距离+2;
                {
                    d[j] = d[t] + 2;
                }
                else d[j] = d[t] + 1;//否则为向下走
                q[++tt] = j;
            }
        }
    }
}
int main()
{
    memset(h, -1, sizeof h);
    cin >> n;
    for(int i=1;i<=n-1;i++)
    {
        cin >> u >> v;
        add(u, v), add(v, u);//用邻接表存无向边
    }
    bfs1();
    cout << deep << endl << width << endl;
    cin >> x >> y;
    bfs2(x);
    cout << d[y];
    return 0;
}
```1. 
2023/7/25 20:50
加载中...