2017-04-26 82 views
0

笔 - 测试用例数| 1 < = T < = 10和n - 元素的数量| 1 < = N < = 1000000爪哇:2D阵列的总和,其中所述M [i] [j] =(int)的I/J,

例如

if (T >= 1 && T <= 10) { 
    for (int i = 0; i < T; i++) { 
       int n = sc.nextInt(); 
       if (n > 0 && n <= 1000000) { 
        array = new int[n][n]; 
        System.out.print("\n" + sumOfArray(array, n)); 
       } 
      } 
      } 

需要找到M [i] [j],其中M [i] [j] =(int)的I/j的总和;

我写的代码,但对于N> 10000,我开始越来越OOM,(出于显而易见的原因)。

如果有人能帮助我与它,它会是巨大的。需要一种全新的方法来解决问题。

例如,

Input Output 
2  
2  4 
4  17 
+0

I> = 1且j> = 1。 – iamvroon

回答

2

这里很明显,你不需要将值存储在矩阵,因为它是不可能有那么大的空间(Array[10000][10000])来分配。所以你需要用mathematical的方式来思考。

考虑一个4x4矩阵和代表的i,j术语的每个元素。

1,1 1,2 1,3 1,4 
2,1 2,2 2,3 2,4 
3,1 3,2 3,3 3,4 
4,1 4,2 4,3 4,4 

现在我们可以在这里表示存储在每个元素中的内容。

1/1 1/2 1/3 1/4 (In Integers)  1 0 0 0 
2/1 2/2 2/3 2/4 ============>  2 1 0 0 
3/1 3/2 3/3 3/4      3 1 1 0 
4/1 4/2 4/3 4/4      4 2 1 1 

通过将其分成列解决这个矩阵和解决每个columns的。 对于第一列系列将1+2+3+4。然后对列号two(2)系列将0+1+1+2

请注意,对于ithfirsti-1值为零,然后i values在列中相同。然后value增加。 i值也是一样。再次增加1等。

所以在ith列值获得increasedjth元素,其中j%i==0上。

所以你可以在1-D数组中实现这个逻辑,对于每个测试用例,这种方法的复杂度将是O(n logn)

代码:

import java.util.Scanner; 

public class Main 
{ 
    public static void main(String args[]) 
    { 
     Scanner sc=new Scanner(System.in); 

     int testcases=sc.nextInt(); 

     while(testcases-- >0) 
     { 
      int n=sc.nextInt(); 

      long array[]=new long[n+1]; //Take long array to avoid overflow 

      for(int i=1;i<=n;i++) 
      { 
       for(int j=i;j<=n;j+=i) 
       { 
        array[j]++;   //This will store that which elements get increased 
             //from zero how many times 
       } 
      } 

      //Now we can do summation of all elements of array but we need to do prefix sum here 

      long sum=0; 
      for(int i=1;i<=n;i++) 
      { 
       array[i]+=array[i-1]; 
       sum+=array[i]; 
      } 

      System.out.println(sum); 
     } 
    } 
} 
+0

谢谢Sanket。实际上是在思考同一条线。得到了我正在寻找的答案。 – iamvroon