zoukankan      html  css  js  c++  java
  • 病毒传播, 美团笔试题

    暴力寻找每个被感染的点是否是起点v。对于每个起点v,广度优先遍历扩散一遍,扩散后结果和S集相同,则v是可能结果。

    import java.util.*;
    public class Main {
        static boolean bfs(Set<Integer>[] g, int n, int x, boolean[] infected, int t, int k) {
            LinkedList<Integer> q = new LinkedList<>();
            Set<Integer> set = new HashSet<>();//存当前扩散到的点
            q.offer(x); set.add(x);
            int distance = 0;// 记录是第几天扩散到点
            while(!q.isEmpty()) {
                int size = q.size(); 
                distance ++;
                if(distance > t) break;// 超过t天,不需要继续了
                for(int i=0; i < size; i++) {
                    int cur = q.poll();
                    for(int v : g[cur]) {
                        if(set.contains(v)) continue;//已经被访问,直接跳过
                        if(infected[v] == false) {
                            return false; //以x为起点,扩散到v,但实际v未被感染,因此,x一定非起点
                        }
                        q.offer(v); set.add(v);
                    }
                }
            }
            //当t天后,扩散到的点刚好为k个时,符合题意。否则x一定不是起点
            if(set.size() == k) return true;
            return false;
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt(), m = sc.nextInt();
            Set<Integer>[] g = new HashSet[n+1]; // 去除重边
            for(int i=1; i <= n; i++) g[i] = new HashSet<Integer>();
            for(int i=0; i < m; i++) {
                int u = sc.nextInt(), v = sc.nextInt();
                if(u != v) { //去除自环
                    g[u].add(v); g[v].add(u);
                }
            }
            int k =sc.nextInt(), t = sc.nextInt();
            boolean[] infected = new boolean[n+1];
            List<Integer> res = new ArrayList<>();
            for(int i=0; i < k; i++) {
                int v = sc.nextInt();
                infected[v] = true;
            }
            for(int i=1; i <= n; i++) { // 暴力找起点
                if(infected[i] && bfs(g, n, i, infected, t, k)) 
                    res.add(i);
            }
            if(res.size() == 0) {
                System.out.println("-1");
            } else {
                for(int i=0; i < res.size()-1; i++) 
                    System.out.print(res.get(i)+" ");
                System.out.println(res.get(res.size()-1));
            }
        }
    }
    
  • 相关阅读:
    一、服务器控件生命周期
    ArcGIS中的Analysis Tool中的Overlay
    谓词和操作
    联接基础知识SQL中
    修改windows右键菜单
    二、服务器控件的呈现
    连接池
    数据库中的NULL(空值)
    有关在SQL中使用函数
    锁的概述及例子讲解(转贴)
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13222068.html
Copyright © 2011-2022 走看看