• NYOJ 20 吝啬的国度


    吝啬的国度

    时间限制:1000 ms  |  内存限制:65535 KB
    难度:3
     
    描述
    在一个吝啬的国度里有N个城市,这N个城市间只有N-1条路把这个N个城市连接起来。现在,Tom在第S号城市,他有张该国地图,他想知道如果自己要去参观第T号城市,必须经过的前一个城市是几号城市(假设你不走重复的路)。
     
    输入
    第一行输入一个整数M表示测试数据共有M(1<=M<=5)组
    每组测试数据的第一行输入一个正整数N(1<=N<=100000)和一个正整数S(1<=S<=100000),N表示城市的总个数,S表示参观者所在城市的编号
    随后的N-1行,每行有两个正整数a,b(1<=a,b<=N),表示第a号城市和第b号城市之间有一条路连通。
    输出
    每组测试数据输N个正整数,其中,第i个数表示从S走到i号城市,必须要经过的上一个城市的编号。(其中i=S时,请输出-1)
    样例输入
    1
    10 1
    1 9
    1 8
    8 10
    10 3
    8 6
    1 2
    10 4
    9 5
    3 7
    
    样例输出
    -1 1 10 10 9 8 3 1 1 8
    /*WA*/
    import java.util.Scanner;
    
    public class 吝啬的国度{
        static class Edge{ //邻接表
            int v;
            int next;
            //int weight; 这里不需要
        }
        static int[] first;// first[]头结点数组
        static int tot;
        static int n; //节点数,边数
        static Edge[] edge; //
        
        static int[] pre;
        public static void main(String[] args) {
             Scanner sc = new Scanner(System.in);
             int tcase = sc.nextInt();
             while(tcase-->0){
                 n = sc.nextInt();
                 int S = sc.nextInt();
                 tot=0;
                 edge = new Edge[2*n+1];
                 first = new int [2*n+1];
                 for(int i=1;i<=n;i++){
                        first[i] = -1;
                }
                 pre = new int[n+1];
                 pre[S]=-1;
                 for(int i=0;i<n-1;i++){
                     int u = sc.nextInt();
                     int v = sc.nextInt();
                     addEdge(u, v);//由于是双向的
                     addEdge(v, u);
                 }
                 DFS(S);
                 for(int i=1;i<n;i++)
                     System.out.print(pre[i]+" ");
                 System.out.println(pre[n]);
             }
        }
        private static void DFS(int s) {
            for(int i=first[s];i!=-1;i=edge[i].next){
                if(pre[edge[i].v]!=0) continue;
                pre[edge[i].v]=s;
                DFS(edge[i].v);
            }
        }
        private static void addEdge(int u, int v) { //构建邻接表 
            edge[tot] = new Edge();
            edge[tot].v = v;
            edge[tot].next = first[u];
            first[u] = tot++;
        }
    }
  • 相关阅读:
    python加速包numba并行计算多线程
    idea Exception in thread "http-apr-8080-exec-2" java.lang.OutOfMemoryError: PermGen space
    centos6.5 导入matplotlib报错 No module named '_tkinter
    pythonTensorFlow实现yolov3训练自己的目标检测探测自定义数据集
    ajax post请求json数据在spring-controller解析
    python keras YOLOv3实现目标检测
    mybatis 插入语句name no find
    python调用百度语音识别接口实时识别
    idea ssm框架搭建
    OpenCVSSDpython目标探测对象检测
  • 原文地址:https://www.cnblogs.com/liyinggang/p/5170906.html
Copyright © 2020-2023  润新知