有向无权图的最短路径

2023-06-27  本文已影响0人  摇摆苏丹
#define _CRT_SECURE_NO_WARNINGS
#include <unordered_map>
#include <vector>
#include <queue>
using namespace std;

struct Line
{
    bool visited = false;
    int length = 0;
    int from = -1;
};

int main()
{
    unordered_map<int, vector<int>> adj_list;
    FILE *fptr = fopen("input.txt", "r");

    int node_cnt;
    fscanf_s(fptr, "%d", &node_cnt);
    for (int i = 0; i < node_cnt; i++)
    {
        int node;
        fscanf_s(fptr, "%d", &node);
        vector<int> empty;
        adj_list[node] = empty;
    }

    int edge_cnt;
    fscanf_s(fptr, "%d", &edge_cnt);
    for (int i = 0; i < edge_cnt; i++)
    {
        int start;
        int end;
        fscanf_s(fptr, "%d%d", &start, &end);
        adj_list[start].push_back(end);
    }

    int start_idx;
    fscanf_s(fptr, "%d", &start_idx);

    vector<Line> table;
    for (int i = 0; i < node_cnt; i++)
    {
        Line line;
        table.push_back(line);
    }

    queue<int> q;
    q.push(start_idx);

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

        if (table[cur_idx].visited)
        {
            continue;
        }
        table[cur_idx].visited = true;

        for (int idx : adj_list[cur_idx])
        {
            if (table[idx].from != -1)
            {
                continue;
            }
            table[idx].from = cur_idx;
            table[idx].length = table[cur_idx].length + 1;
            q.push(idx);
        }
    }

    return 0;
}
7
0
1
2
3
4
5
6
10
0   1
0   6
0   5
1   2
2   3
2   6
3   6
3   4
4   5
6   5
0
上一篇 下一篇

猜你喜欢

热点阅读