zoukankan      html  css  js  c++  java
  • 团体程序设计天梯赛 L3-008 喊山 (30分)(BFS)

    题目链接:

    L3-008 喊山 (30分)

    思路:

    以给定的点为源点进行bfs即可

    代码:

    #include<bits/stdc++.h>
    
    using namespace std;
    
    inline int read() {
    	int x = 0; char c;
    	while(c = getchar(), c < '0' || c > '9');
    	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    	return x;
    }
    
    const int maxn = 1e4 + 5;
    vector<int> G[maxn];
    int d[maxn];
    
    void bfs(int u) {
    	if(G[u].size() == 0) { puts("0"); return; }
    	d[u] = 1;
    	queue<int> que;
    	que.push(u);
    	int ans = u;
    	while(!que.empty()) {
    		int now = que.front();
    		if(d[now] == d[ans] ? now < ans : d[now] > d[ans]) ans = now;
    		que.pop();
    		for(int & x : G[now]) if(!d[x]) d[x] = d[now] + 1, que.push(x);
    	}
    	cout << ans << '
    ';
    }
    
    int main() {
    #ifdef MyTest
    	freopen("Sakura.txt", "r", stdin);
    #endif
    	int n = read(), m = read(), k = read();
    	for(int i = 0; i < m; i++) {
    		int x = read(), y = read();
    		G[x].push_back(y);
    		G[y].push_back(x);	
    	}
    	while(k--) {
    		int q = read();
    		fill(d, d + n + 1, 0);
    		bfs(q);
    	}
    	return 0;
    }
    
    
  • 相关阅读:
    collections工具类 排序
    API text|lang
    异常处理
    extends继承
    接口
    static修饰符
    多态与find关键词
    Markdown语法
    Hexo | (五)Yilia主题优化
    Hexo | (四)多机同步更新博客
  • 原文地址:https://www.cnblogs.com/yuhan-blog/p/12308626.html
Copyright © 2011-2022 走看看