hiho 1624 最短游览路线 [Offer收割]编程练习赛35 Problem B

来源:互联网 发布:小猪o2o源码下载 编辑:程序博客网 时间:2024/05/23 11:38

题目2 : 最短游览路线

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

十一期间小Hi被朋友拉去某座名山旅游。这座山上一共有N个景点,编号1~N,通过M条单向缆车相连。  

小Hi和朋友的出发点在1号景点。小Hi正在等待某公司的面试电话,所以他希望找一条路线,搭乘最少次数的缆车(至少一次),回到出发点。  

你能求出最少搭乘缆车的次数吗?

输入

第一行包含两个整数N和M。  

以下M行,每行包含两个整数a和b,代表有一条从a到b的单向缆车。  

对于30%的数据,1 ≤ N ≤ 10, 1 ≤ M ≤ 90

对于100%的数据,1 ≤ N ≤ 10000, 1 ≤ M ≤ 100000, 1 ≤ a, b ≤ N, a ≠ b

输出

回到出发点最少搭乘缆车的次数。如果无法通过缆车回到出发点输出-1。

样例输入
5 7  1 2  5 1  2 4  2 3  3 2  3 4  4 5
样例输出
4
bfs一下就行

#include <iostream>#include <stdio.h>#include <math.h>#include <stdlib.h>#include <string>#include <string.h>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <stack>#include <bits/stdc++.h>using namespace std;int N,M;vector<int>G[10009];bool used[100009];struct node{    int v,step;    node(){}    node(int V,int S){        v=V;        step=S;    }};int bfs(){    queue<node>q;    if(G[1].size()==0)return -1;    for(int i=0;i<G[1].size();i++){        q.push(node(G[1][i],1));        used[G[1][i]]==1;    }    while(!q.empty()){        node cur=q.front();        q.pop();        if(cur.v==1)return cur.step;        for(int i=0;i<G[cur.v].size();i++){            if(!used[G[cur.v][i]]){                q.push(node(G[cur.v][i],cur.step+1));                used[G[cur.v][i]]=1;            }        }    }    return -1;}/*5 51 25 12 33 24 5*/int main(){    cin>>N>>M;    for(int i=0;i<M;i++){        int a,b;        scanf("%d%d",&a,&b);        G[a].push_back(b);    }    cout<<bfs();    return 0;}////                       _oo0oo_//                      o8888888o//                      88" . "88//                      (| -_- |)//                      0\  =  /0//                    ___/`---'\___//                  .' \\|     |// './/                 / \\|||  :  |||// \//                / _||||| -:- |||||- \//               |   | \\\  -  /// |   |//               | \_|  ''\---/''  |_/ |//               \  .-\__  '-'  ___/-. ///             ___'. .'  /--.--\  `. .'___//          ."" '<  `.___\_<|>_/___.' >' "".//         | | :  `- \`.;`\ _ /`;.`/ - ` : | |//         \  \ `_.   \_ __\ /__ _/   .-` /  ///     =====`-.____`.___ \_____/___.-`___.-'=====//                       `=---='//////     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~////               佛祖保佑         永无BUG//////





阅读全文
1 0
原创粉丝点击