POJ 2457 Part Acquisition - (BFS最短路打印)

题目链接:http://poj.org/problem?id=2457

#include <stdio.h>  
#include <vector>   
#include <algorithm>
#include <queue>
using namespace std;

//POJ 2457 Part Acquisition

struct Edge
{
    int in, out;
    Edge() {}
    Edge(int _in, int _out) :
        in(_in), out(_out) {}
};

void print(int* precursor, int K)
{
    int *tmp = new int[K];
    int count = 0;
    int cur = K - 1;
    while (cur >= 0)
    {
        tmp[count] = cur;
        cur = precursor[cur];
        count++;
    }
    printf("%d\n", count);
    for (int i = count - 1; i >= 0; --i)
        printf("%d\n", tmp[i] + 1);
    delete[] tmp;
}


int main()
{
    int N, K;
    while (~scanf("%d%d", &N, &K))
    {

        vector<vector<int> > nodes(K);
        vector<Edge> edges(N);
        for (int i = 0; i < N; ++i)
        {
            int in, out;
            scanf("%d%d", &in, &out);
            in--; out--;
            edges[i] = Edge(in, out);
            nodes[in].push_back(i);
        }
        //BFS
        bool *mark = new bool[K];
        int *precursor = new int[K];
        for (int i = 0; i < K; ++i)
        {
            mark[i] = false;
            precursor[i] = -1;
        }
        mark[0] = true;

        queue<int> q;
        q.push(0);
        while (!q.empty())
        {
            const int node_id = q.front(); q.pop();
            const int size = nodes[node_id].size();
            for (int i = 0; i < size; ++i)
            {
                const int edge_num = nodes[node_id][i];
                const int out = edges[edge_num].out;
                if (mark[out])continue;
                q.push(out); mark[out] = true;
                precursor[out] = node_id;
            }
        }
        if (mark[K - 1])print(precursor, K);
        else printf("-1\n");
        delete[] mark;
    }

    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值