27.數軸上兩個點集距離問題


 同一個數軸x有兩個點的集合A={A1,A2,...,Am}和B={B1,B2,...,Bm}  A(i)和B(j)均為正整數
 A、B已經按照從小到大排好序,AB均不為空
給定一個距離R 正整數,列出同時滿足如下條件的(A(i),B(j))數對
1. A(i)<=B(j)
2. A(i),B(j)之間距離小於等於R
3. 在滿足1,2的情況下每個A(i)只需輸出距離最近的B(j)
4. 輸出結果按A(i)從小到大排序

輸入描述
第一行三個正整數m n R
第二行m個正整數 表示集合A
第三行n個正整數 表示集合B

輸入限制
1<=R<=100000
1<=n,m<=100000
1<= A(i),B(j) <= 1000000000

輸出描述
每組數對輸出一行 A(i)和B(j),以空格隔開

示例一
輸入
4 5 5
1 5 5 10
1 3 8 8 20

輸出
1 1
5 8
5 8

查看代碼

import java.util.*;

public class Demo27 {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int m = Integer.parseInt(s.split(" ")[0]);
        int n = Integer.parseInt(s.split(" ")[1]);
        int r = Integer.parseInt(s.split(" ")[2]);
        String[] splitA = sc.nextLine().split(" ");
        String[] splitB = sc.nextLine().split(" ");

        int[] intsA = new int[m];
        int[] intsB = new int[n];

        for(int i = 0; i < m; i++){
            intsA[i] = Integer.parseInt(splitA[i]);
        }
        for(int i = 0; i < n; i++){
            intsB[i] = Integer.parseInt(splitB[i]);
        }

        //因為是從小到大有序的,而且要求輸出距離最近的Bj,所以省去了很多情況
        for(int i : intsA){
            for(int j : intsB){
                if(i <= j && j - i < r){
                    System.out.println(i + " " + j);
                    break;
                }
            }
        }
    }
}

總結:有的時候,條件很多,但是很多狀況因為一些要求已經排除掉,不需要分類考慮。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM