问题
import java.util.Scanner;
class Special_Pairs{
private static Scanner scan;
public static void main(String [] args) {
byte t;
int n;
scan = new Scanner(System.in);
t=scan.nextByte();
int[] a=new int[100000];
while(t>0)
{
int i,j,count=0;
n=scan.nextInt();
for(i=0;i<n;i++)
{
a[i]=scan.nextInt();
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(((a[i]&a[j])==0)||((a[j]&a[i])==0))
{
count++;
}
}
}
t--;
System.out.println(count);
}
}
}
Help me reduce time complexity of this program
Question :
You have been given an integer array A on size N. You must report the number of ordered pairs (i,j)
such that A[i] & A[j]=0
.
Here &
denotes the BITWISE AND
(i,j)
and (j,i)
are considered different.
Input: First line contains T-Number of Test cases. First line of each test contains N. Next line contains N integers - the i'th integer A[i].
Output: Output the number of such pairs for each test case.
Constraints: T ≤ 10; N ≤ 100000; A[i] ≤ 1000000
Sample Input(Plaintext Link)
1
5
41 47 34 40 29
Sample Output(Plaintext Link)
2
Explanation: These are the required pairs (3 5)
(5 3)
回答1:
I would suggest three optimization for this. I have modified the code as well.
- You need not to always start from 0 for each iteration of outer loop. The second loop can start from
current+1
of the first loop. So will not be comparing elements which you have already compared. - You don't need to check for both pairs
(i,j)
and(j,i)
. If one is zero then other will always be zero. - You need not to initialize the array with fix size. You can always initialize it reading the value of
n
.
import java.util.Scanner;
public class Pairs {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t > 0) {
t--;
int count = 0;
int n = scan.nextInt();
int a[] = new int[n];
for(int i = 0; i<n; i++) {
a[i]=scan.nextInt();
}
for(int i = 0; i<n-1; i++) {
for(int j = i+1; j<n; j++) {
if((a[i] & a[j])==0)
{
count += 2;
}
}
}
System.out.println(count);
}
}
}
回答2:
If you are competing on a programming contest (like ICPC or something like this), maybe you shouldn't use Scanner
. It's too slow for reading from the keyboard. I've already competed at ICPC, but I used to use C++. Maybe you should try BufferedReader
instead of Scanner
.
来源:https://stackoverflow.com/questions/32405298/reduce-time-complexity-of-the-following-program