算法训练---平穷的城市

问题描述

  某城市有n个小镇,编号是1~n。由于贫穷和缺乏城市规划的人才,每个小镇有且仅有一段单向的公路通往别的小镇。有一天,一辆小轿车误入了这座城市,它只能沿着公路走,它走啊走,却再也走不出这座城市了……
  问如果这辆车从某个小镇出发,走了若干段公路,会到达哪个小镇。每组数据有m个询问。

输入格式

  第一行两个数n、m:表示小镇数和询问数;
  接下来一行n个数,第i个数Ai:表示从小镇i出发的公路会通向小镇Ai;
  接下来m行,第i行有两个数Bi和Ci:询问小轿车从小镇Bi出发,走过Ci段路后会达到哪个小镇。

输出格式

  一行m个数回答每个询问。

样例输入

3 3
2 1 3
1 1
2 2
3 3

样例输出

2 2 3

import java.util.Scanner;
public class Main {
public static void main(String [] args) {
        Scanner scanner =new Scanner(System.in);
    int n=scanner.nextInt();
    int m=scanner.nextInt();
    int Ai[]=new int[n];
    int question[][]=new int[m][2];
    
    for(int i=0;i<n;i++) { 
        Ai[i]=scanner.nextInt();
    }
    
    for(int i=0;i<m;i++) {
        for(int j=0;j<2;j++) {
         question[i][j]=scanner.nextInt();
        }
    }
    
    for(int i=0;i<m;i++) {
       int stepCount= question[i][1];
        int startPlace=question[i][0];
        while(stepCount>0) {
            startPlace=Ai[startPlace-1];
            stepCount--;
        }
        
        System.out.print(startPlace+" ");
    }
    
    
}

}

下面的代码借鉴与以为博主


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(), m = scanner.nextInt();
        int a[][] = new int[n][18], b, c;
        for (int i = 0; i < n; ++i) {
            a[i][0] = scanner.nextInt() - 1;
        }
        for (int j = 1; j < 18; ++j) {
            for (int i = 0; i < n; ++i) {
                a[i][j] = a[a[i][j - 1]][j - 1];
            }
        }//上面都是预处理内容
        int end = 0;
        //下面是将c拆分为几个2^j
        for (int i = 0; i < m; ++i) {
            b = scanner.nextInt() - 1;
            c = scanner.nextInt();
            end = b;
            int count = 0;
            if (c == 0) {// 因为end=b,不写也没事
                System.out.print(b + 1 + " ");
                continue;
            }
            while (c != 0) {
                if (c % 2 == 1)
                    end = a[end][count];
                c = c / 2;
                count++;
            }
            System.out.print(end + 1 + " ");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_62994974/article/details/128554295
今日推荐