小易有一个长度为N的正整数数列A = {A[1], A[2], A[3]..., A[N]}。牛博士给小易出了一个难题:
对数列A进行重新排列,使数列A满足所有的A[i] * A[i + 1](1 ≤ i ≤ N - 1)都是4 的倍数。
小易现在需要判断一个数列是否可以重排之后满足牛博士的要求。
2021-10-27 更新如下:
思路比看到的其他简单点,不知是否仍有没考虑到的case。
因任意偶数相乘均为4 的倍数;
即 2n * 2m = 4(n * m)
且任意4n (4的倍数) 与奇数相乘均为4 的倍数;
即 4n * m
且奇偶(非四倍数)相乘,不为4 的倍数;
2n * (2n+1) = 4n^2 + 2n
。。。 反正是永远不为4 倍数,基础不行 写不出过程。
故可忽略偶数,只判断4n 数量与奇数 数量 1:1 即是符合条件。
public class Main {
private static String f(ArrayList<Integer> arr) {
int count4 = 0;
int countOdd = 0;
for (Integer num : arr) {
if (num % 4 == 0) {
count4++;
} else if ((num & 1) == 1) {
countOdd++;
}
}
return count4 >= countOdd ? "Yes" : "No";
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Integer> list1 = new ArrayList<>();
for (int i = 0; i < n; i++) {
int count = 0;
if (sc.hasNextInt())
count = sc.nextInt();
for (int j = 0; j < count; j++) {
list1.add(sc.nextInt());
}
System.out.println(f(list1));
}
}
}
=============== 错误的old code 分割线 ===============
import java.util.ArrayList;
import java.util.Scanner;
/**
* 100 1 10
* A[i] * A[i+1] % 4 == 0
*
* @author Asus
*
*/
public class Main {
private static String f(ArrayList<Integer> arr){
int count = 0 ;
for (Integer object : arr) {
if ( object % 4 == 0 ) {
count++;
}
}
if ( count >= arr.size()/2) {
return "Yes";
}
return "No";
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int count = 0;
if(sc.hasNextInt())
count = sc.nextInt();
for (int j = 0; j < count; j++) {
list1.add(sc.nextInt());
}
System.out.println(f(list1));
}
}
}