2018蓝桥杯之递增三元组

标题:递增三元组

给定三个整数数组
A = [A1, A2, … AN],
B = [B1, B2, … BN],
C = [C1, C2, … CN],
请你统计有多少个三元组(i, j, k) 满足:

  1. 1 <= i, j, k <= N
  2. Ai < Bj < Ck

【输入格式】
第一行包含一个整数N。
第二行包含N个整数A1, A2, … AN。
第三行包含N个整数B1, B2, … BN。
第四行包含N个整数C1, C2, … CN。
对于30%的数据,1 <= N <= 100
对于60%的数据,1 <= N <= 1000
对于100%的数据,1 <= N <= 100000 0 <= Ai, Bi, Ci <= 100000
【输出格式】
一个整数表示答案

【输入样例】
3
1 1 1
2 2 2
3 3 3

【输出样例】
27

资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms

解法一:
首先想到的是暴力求解,三个循环依次遍历,当然时间复杂度明显太高,O(n3)

解法二:
简单想了一下,首先应该录入数据过后,就使用jdk自带的 Arrays.sort()方法,让数组直接拍好序。
然后把中间的数组也就是B数组,当做判断中介,先判断B和C,再判断A和B来计算有多少个满足条件,然后乘起来。

本人水平有限,这样的时间复杂度稍微好一点 O(n2)
import java.util.Arrays;
import java.util.Scanner;

public class Main{
	
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt();
		int[] A = new int[N];
		int[] B = new int[N];
		int[] C = new int[N];
		
		for(int i=0;i<N;i++) {
			A[i] = scanner.nextInt();
		}
		Arrays.sort(A);
		
		for(int i=0;i<N;i++) {
			B[i] = scanner.nextInt();
		}
		Arrays.sort(B);
		
		for(int i=0;i<N;i++) {
			C[i] = scanner.nextInt();
		}
		Arrays.sort(C);
		
		System.out.println(jisuan(A, B, C, N));
		
		
	}
	
	
	public static int jisuan(int[] A,int[] B,int[] C,int N) {
		
		int[] temp = new int[N];
		int temp_count ;
		
		for(int i=0;i<N;i++) {
			temp_count = 0;
			for(int j=0;j<N;j++) {
				
				if(B[i]<C[j]) {
					temp[i]++;
				}
				if(A[j]<B[i]) {
					temp_count++;
				}
			}
			temp[i] *= temp_count;
		}
		
		int sum = 0;
		for(int i=0;i<N;i++) {
			sum+=temp[i];
		}
		return sum;
		
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/weixin_42036647/article/details/88533263