要求:
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 128M,其他语言256M
题目内容:
给定N(可选作为埋伏点的建筑物数)、D(相距最远的两名特工间的距离的最大值)以及可选建筑的坐标,计算在这次行动中,大锤的小队有多少种埋伏选择。
注意:
1. 两个特工不能埋伏在同一地点
2. 三个特工是等价的:即同样的位置组合(A, B, C) 只算一种埋伏方法,不能因“特工之间互换位置”而重复使用
输入描述:
第一行包含空格分隔的两个数字 N和D(1≤N≤1000000; 1≤D≤1000000)
第二行包含N个建筑物的的位置,每个位置用一个整数(取值区间为[0, 1000000])表示,从小到大排列(将字节跳动大街看做一条数轴)
输出描述:
一个数字,表示不同埋伏方案的数量。结果可能溢出,请对 99997867 取模
输入例子1:
4 3
1 2 3 4
输出例子1:
4
例子说明1:
可选方案 (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)
输入例子2:
5 19
1 10 20 30 50
输出例子2:
1
例子说明2:
可选方案 (1, 10, 20)
代码:
import java.util.Scanner;public class Main {public static void main(String[] args) {question();}public static void question() {Scanner sc = new Scanner(System.in);// 输入第一行内容String firstLine = sc.nextLine();// 输入第二行内容String secondLine = sc.nextLine();// 按照空格分隔字符串String[] firstArr = firstLine.split(" ");String[] secondArr = secondLine.split(" ");// 建筑物的数量int N = Integer.parseInt(firstArr[0]);// 两名特工间的最大距离int D = Integer.parseInt(firstArr[1]);// 建筑物的位置int[] locations = new int[N];for (int i = 0; i < secondArr.length; i++) {locations[i] = Integer.parseInt(secondArr[i]);}int left = 0, right = 2;// 符合条件的方案个数long count = 0L;while (right < N) {if (locations[right] - locations[left] > D) {left++;} else if (right - left < 2) {right++;} else {count += calCulateCount(right - left);right++;}}count = count % 99997867;System.out.println(count);}/*** 计算满足条件的建筑物有几种选择方案* @param num* @return*/public static long calCulateCount(long num) {return num * (num - 1) / 2;}
}