• 天梯赛练习 L3-008 喊山 (30分) bfs搜索


    题目分析:

    本题是一题比较简单的bfs搜索题,首先由于数据给的比较多不能直接开二维数组存放,而是用了vector的动态的二维数组的形式存放,对于每个出发点,我们bfs向四周搜索,标记搜索过的点,遇到搜过的点就可以停止搜索了,每次搜一个点就和全局的最远距离比较,更远则代替,相同则比较此时编号的大小,如果编号更小则也可以代替

    本题代码:

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<string.h>
     4 #include<queue>
     5 #include<vector>
     6 #include<algorithm>
     7 using namespace std;
     8 
     9 const int N = 10005;
    10 int vis[N];
    11 vector<int> v[N];
    12 int length, number, n, m, k;
    13 struct Node{
    14     int id, len;
    15 };
    16 
    17 void bfs(int x){
    18     number = 0;
    19     length = 0;
    20     memset(vis, 0, sizeof(vis));
    21     queue<Node> q;
    22     Node sta;
    23     sta.id = x;
    24     sta.len = 0;
    25     if(v[sta.id].size() == 0) printf("0
    ");
    26     else{
    27         q.push(sta);
    28         vis[sta.id] = 1; 
    29         while(!q.empty()){
    30             Node temp = q.front();
    31             q.pop();
    32             for(int i = 0; i < v[temp.id].size(); i++){
    33                 int y = v[temp.id][i];
    34                 if(vis[y] == 0){
    35                     Node next;
    36                     next.id = y;
    37                     next.len = temp.len + 1;
    38                     if(next.len > length){
    39                         length = next.len;
    40                         number = next.id;
    41                     }else if(next.len == length && next.id < number){
    42                         number = next.id;
    43                     }
    44                     q.push(next);
    45                     vis[next.id] = 1;
    46                 }
    47             }
    48         }
    49         printf("%d
    ", number);
    50     }    
    51 }
    52 
    53 int main(){
    54     scanf("%d%d%d", &n, &m, &k);
    55     for(int i = 1; i <= m; i++){
    56         int a, b;
    57         scanf("%d%d", &a, &b);
    58         v[a].push_back(b);
    59         v[b].push_back(a);
    60     }
    61     for(int i = 1; i <= k; i++){
    62         int sta;
    63         scanf("%d", &sta);
    64         bfs(sta);        
    65     }
    66     return 0;
    67 }
  • 相关阅读:
    能够免费做商业站点的CMS讨论
    ntoskrnl.exe损坏或丢失的解决方式
    QT 仓库管理系统 开放源代码
    Disposable microfluidic devices: fabrication, function, and application Gina S. Fiorini and Daniel T
    DllImport中的EntryPoint
    IOS Table中Cell的重用reuse机制分析
    双slave的server_uuid同样问题
    怎样使用SetTimer MFC 够具体
    2013 成都邀请赛
    设计模式六大原则(2):里氏替换原则
  • 原文地址:https://www.cnblogs.com/findview/p/12264246.html
Copyright © 2020-2023  润新知