zoukankan      html  css  js  c++  java
  • poj2457

    最短路

    View Code
    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #include <cstdio>
    using namespace std;

    #define maxm 50005
    #define maxn 1005

    struct Edge
    {
    int v, next;
    }edge[maxm * 2];

    int n, m;
    int head[maxn];
    int ecount;
    int from[maxn];
    int q[maxn];
    int stk[maxn];
    bool vis[maxn];

    void addedge(int a, int b)
    {
    edge[ecount].v = b;
    edge[ecount].next = head[a];
    head[a] = ecount++;
    }

    void input()
    {
    scanf("%d%d", &m, &n);
    ecount = 0;
    memset(head, -1, sizeof(head));
    for (int i = 0; i < m; i++)
    {
    int a, b;
    scanf("%d%d", &a, &b);
    a--;
    b--;
    addedge(a, b);
    }
    }

    void bfs()
    {
    memset(vis, 0, sizeof(vis));
    int front = 0;
    int rear = 0;
    q[rear++] = 0;
    vis[0] = true;
    while (front != rear)
    {
    int u = q[front++];
    for (int i = head[u]; i != -1; i = edge[i].next)
    {
    int v = edge[i].v;
    if (!vis[v])
    {
    from[v] = u;
    q[rear++] = v;
    vis[v] = true;
    if (v == n - 1)
    return;
    }
    }
    }
    }

    void print()
    {
    int a = n - 1;
    int top = 0;
    while (a != 0)
    {
    stk[top++] = a;
    a = from[a];
    }
    stk[top++] = 0;
    printf("%d\n", top);
    for (int i = top - 1; i >= 0; i--)
    printf("%d\n", stk[i] + 1);
    }

    int main()
    {
    //freopen("t.txt", "r", stdin);
    input();
    bfs();
    if (!vis[n - 1])
    printf("-1\n");
    else
    print();
    return 0;
    }

  • 相关阅读:
    [saiku] 系统登录成功后查询Cubes
    216. Combination Sum III
    215. Kth Largest Element in an Array
    214. Shortest Palindrome
    213. House Robber II
    212. Word Search II
    211. Add and Search Word
    210. Course Schedule II
    分硬币问题
    开始学习Python
  • 原文地址:https://www.cnblogs.com/rainydays/p/2197987.html
Copyright © 2011-2022 走看看