在我们的X轴上有N个士兵。士兵所在的地点也有一定数量的炸弹。战争迫在眉睫,每个士兵都想和其他士兵交流。如果i-th
士兵具有b个炸弹并且位于位置X,则与具有位于位置Y的c个炸弹的任何其他士兵j的通信成本被定义为|X-Y|*max(b,c)
。如果每个士兵都想要与其他士兵进行通信,则找出通信成本的总和。注意:-你只需考虑一次成本总和的(i,j)对。
输入格式:
第一行由多个测试用例T组成。每个测试用例由三行组成。第一行表示士兵的数量(N)。第二行表示N个士兵的坐标( Xi )。第三行包含每个士兵位置的炸弹数量( Bi )。X坐标不必在输入中按递增顺序排列。约束条件
1 <= T <= 20 1 <= N <= 200000 1 <= X[i] <= 1000000000 1 <= B[i] <= 10000
输出格式:
总成本模数10^9+7。示例输入
1
3
1 3 6
10 20 30
样本输出
280
解释
有3对(1,2) ->开销= abs(3-1) * 20 = 40 (1,3) ->开销= abs(1-6) * 30 = 150 (2,3) ->开销= abs(3-6) * 30 = 90 sum = 40 + 150 + 90 = 280
我正在使用暴力来处理模(10^9+7)和所有东西,但是在下面获取the代码它也适用于上面的情况,但是它是那些恼人的the/类型转换类型问题之一。任何回应都是非常感谢的-
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v= x[i]%(Math.pow(10,9)+7)-x[j]%(Math.pow(10,9)+7);
v=Math.abs(v)%(Math.pow(10,9)+7);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
} }
发布于 2019-12-18 20:18:03
正如@Erwin所建议的,不要在for
循环的每次迭代中使用Math.pow()
计算三次(10^9)+7
。相反,将其放在循环之外(可能将其定义为常量),然后执行您的操作。
此外,您在运算中对(10^9)+7
常量进行了两次模运算。您确定这就是您要做的操作吗?您在v
的第一次计算中这样做,然后在第二次v
的计算中再次这样做。如果您只需要它作为最终成本,您可以从第一步中删除它。
下面是我的代码,你可以尝试一下:
import java.util.*;
public class Main {
public static void main(String args[]) {
double moduloNumber = (Math.pow(10,9)+7);
Scanner sc= new Scanner(System.in);
System.out.print("Enter the Number of Test Cases (1 <= T <= 20): ");
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
System.out.print("\nEnter the Number of Soldiers (1 <= N <= 200000): ");
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
System.out.print("Enter the Position of Soldier " + (i+1) + " (1 <= X[i] <= 1000000000): ");
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
System.out.print("Enter the Number of Bombs with Soldier " + (i+1) + " (1 <= B[i] <= 10000): ");
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v=(x[i]-x[j]);
v=Math.abs(v)%(moduloNumber);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
}
}
我只是添加了一些print语句,并将模常量移到了循环之外,以减少计算成本。您可以检查这是否解决了问题。
致以敬意,
AJ
https://stackoverflow.com/questions/59381492
复制相似问题