P8708 [蓝桥杯 2020 省 A1] 整数小拼接
使用二分查找寻找可以拼在此数前面的合法的数
import java.math.BigInteger;
import java.util.*;
public class Main{
static long ans=0;
static long[] myarr;
static long[][] hash_table;
static int n;
static long k;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
k=sc.nextLong();
myarr=new long[n];
hash_table=new long[11][n];
for (int i=0;i<n;i++)
{
myarr[i]=sc.nextLong();
}
Arrays.sort(myarr);
for (int i=0;i<n;i++)
{
for (int j=0;j<11;j++)
{
hash_table[j][i]=myarr[i]*(int)Math.pow(10,j);
}
}
for (int i=0;i<n;i++)
{
long now=myarr[i];
int length=0;
while (now!=0)
{
length++;
now/=10;
}
func(length,i);
}
System.out.println(ans);
}
public static void func(int length,int index)
{
int l=0;
int r=n-1;
int res=-1;
while (l<=r)
{
int mid=l+(r-l)/2;
if (hash_table[length][mid]+myarr[index]<=k)
{
res=mid;
l=mid+1;
}
else
{
r=mid-1;
}
}
if (res==-1)
{
return;
}
if (res>=index)
{
res--;
}
ans+=res+1;
}
}