zoukankan      html  css  js  c++  java
  • ACwing847. 图中点的层次

    题目

    分析

    所有边的长度都是1,权值相同,用BFS求最短路

    代码

     1 #include<iostream>
     2 #include<cstring>
     3 #include<algorithm>
     4 #include<queue>
     5 using namespace std;
     6 
     7 const int N = 100010;
     8 int h[N],e[N],ne[N],idx;//有向图,e,en不用N乘2
     9 int n,m;//图的结点和边
    10 int d[N];//记录从1号到各个点的距离
    11 
    12 void add(int a,int b){
    13     e[idx] = b,ne[idx] = h[a],h[a] = idx++;
    14 }
    15 
    16 int bfs(){
    17     queue<int>q;
    18     q.push(1);
    19     d[1] = 0;
    20     
    21     while(!q.empty()){
    22         int t = q.front();
    23         q.pop();
    24         for(int i = h[t];i!=-1;i = ne[i]){
    25             int j = e[i];
    26             if(d[j] == -1){ //检查是否已经访问过
    27                 d[j] = d[t]+1;
    28                 q.push(j);
    29             }
    30         }
    31     }
    32     return d[n];
    33 }
    34 
    35 int main(){
    36     scanf("%d%d",&n,&m);
    37     memset(h,-1,sizeof(h)); //别忘记
    38     for(int i = 0;i < m;i++){
    39         int a,b;
    40         scanf("%d%d",&a,&b);
    41         add(a,b);
    42     }
    43     
    44     memset(d,-1,sizeof(d));
    45     printf("%d",bfs());
    46     return 0;
    47 }

    对于图的存储,一定别忘记对 h 的初始化第37行

     

  • 相关阅读:
    poj3273Monthly Expense
    poj2516Minimum Cost
    poj1201Intervals(差分约束)
    poj3122Pie
    poj3258River Hopscotch
    hdu3308LCIS(线段树区间合并)
    CF1178F2 Long Colorful Strip
    CF906C Party
    [NOI2002]贪吃的九头龙
    CF1178F1 Short Colorful Strip
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14437990.html
Copyright © 2011-2022 走看看