方法1:直接拼接一个数组
import java.util.Scanner;
public class Main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int testcase=sc.nextInt();
for(int i=0;i<testcase;i++) {
int groupnum=sc.nextInt();
int querynum=sc.nextInt();
long[][]arr=new long[groupnum][2];
int count=0;
for(int k=0;k<groupnum;k++) {
arr[k][0]=sc.nextLong();
arr[k][1]=sc.nextLong();
count+=arr[k][1]-arr[k][0]+1;
}
//结果数组,需要时查表即可
long[]result=new long[count];
int m=0;
for(int j=0;j<groupnum;j++) {
for(long k=arr[j][0];k<=arr[j][1];k++) {
result[m++]=k;
}
}
long q;
System.out.print(result[(int)(sc.nextLong()-1)]);
for(int k=1;k<querynum;k++) {
System.out.print(" "+result[(int)(sc.nextLong()-1)]);
}
System.out.println();
}
sc.close();
}
}
方法2:构造一个起始值数组,然后用二分查找定位所在区间
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int testcase=sc.nextInt();
for(int i=0;i<testcase;i++) {
int groupnum=sc.nextInt();
int querynum=sc.nextInt();
long[][]arr=new long[groupnum][2];
for(int k=0;k<groupnum;k++) {
arr[k][0]=sc.nextLong();
arr[k][1]=sc.nextLong();
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] o1, long[] o2) {
return (int)(o1[0]-o2[0]);
}
});
long[]rank=new long[groupnum];
rank[0]=arr[0][0];
for(int k=1;k<groupnum;k++) {
rank[k]=arr[k-1][1]-arr[k-1][0]+rank[k-1]+1;
}
for(int k=0;k<querynum;k++) {
long q=sc.nextLong();
int low=0,high=groupnum-1;
int mid=low+(high-low)/2;
while(low<=high) {
mid=low+(high-low)/2;
if(rank[high]<=q) {
if(k==0)
System.out.print((arr[high][0]-rank[high]+q));
else
System.out.print(" "+(arr[high][0]-rank[high]+q));
break;
}
if(high-low<=1) {
if(k==0)
System.out.print((arr[low][0]-rank[low]+q));
else
System.out.print(" "+(arr[low][0]-rank[low]+q));
break;
}
if(rank[mid]>q) {
high=mid;
} else {
low=mid;
}
}
}
System.out.println();
}
sc.close();
}
}
PS:方法2没有通过oj,找了很久也没找出问题出在哪,囧