加载中...

递增三元组

递增三元组

image-20230329204120698

image-20230329204145281

此题考查暴力,二分

此题未 AC 用了两种方法解题

  1. dfs
  2. binarySearch
  1. dfs

    package lanqiao;
    
    import java.util.Scanner;
    
    public class N172 {
        static int[][] m;
        static int n;
        static long res = 0;
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            n = scanner.nextInt();
            m = new int[4][n + 1];
            for (int i = 1; i <= 3; i++) {
                for (int j = 1; j <= n; j++) {
                    m[i][j] = scanner.nextInt();
                }
            }
            for (int i = 1; i <= n; i++)
                dfs(1, i);
            System.out.println(res);
        }
    
        private static void dfs(int a, int b) {
            if (a == 3) {
                res++;
                return;
            }
            for (int i = 1; i <= n; i++) {
                if (a + 1 <= 3)
                    if (m[a + 1][i] > m[a][b]) {
                        dfs(a + 1, i);
                    }
            }
        }
    }
    
    1. binarySearch
    package test;
    
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class N172 {
    	static int n;
    	static int[] a;
    	static int[] b;
    	static int[] c;
    
    	public static void main(String[] args) {
    		Scanner scanner = new Scanner(System.in);
    		n = scanner.nextInt();
    		a = new int[n + 1];
    		b = new int[n + 1];
    		c = new int[n + 1];
    		for (int i = 1; i <= n; i++)
    			a[i] = scanner.nextInt();
    		for (int i = 1; i <= n; i++)
    			b[i] = scanner.nextInt();
    		for (int i = 1; i <= n; i++)
    			c[i] = scanner.nextInt();
    		Arrays.sort(a);
    		Arrays.sort(c);
    		int res = 0;
    		for (int i = 1; i <= n; i++) {
    			int x1 = search2(1, n, b[i], a);
    			int x2 = search(1, n, b[i], c);
    			res += x1 * (n - x2 + 1);
    		}
    		System.out.println(res);
    	}
    
    	/**
    	 * 找到第一个大于 x 的数的下标
    	 * 
    	 * @param l
    	 * @param r
    	 * @param x
    	 * @param a
    	 * @return
    	 */
    	static int search(int l, int r, int x, int[] a) {
    		while (l <= r) {
    			int mid = (l + r) / 2;
    			if (x < a[mid]) {
    				r = mid - 1;
    			} else {
    				l = mid + 1;
    			}
    		}
    		return l;
    	}
    
    	/**
    	 * 找到第一个小于 x 的下标
    	 * 
    	 * @param l
    	 * @param r
    	 * @param x
    	 * @param a
    	 * @return
    	 */
    	static int search2(int l, int r, int x, int[] a) {
    		while (l <= r) {
    			int mid = (l + r) / 2;
    			if (x <= a[mid]) {
    				r = mid - 1;
    			} else {
    				l = mid + 1;
    			}
    		}
    		return r;
    	}
    }
    

    说明:

    1. dfs 超时
    2. bs 有两个测试点答案错误,有大佬知道哪里有错误还望指正,感谢各位!
posted @ 2023-03-29 19:32  ChuenSan  阅读(12)  评论(0编辑  收藏  举报