平方数
算法原理
数学,先对这个数开根号,取整,求根号值与根号值+1分别的平方,再比较与原数的距离得出结果
代码
import java.util.Scanner;
public class Main {
//注意,一定要开long
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
long a = (int)Math.sqrt(n);
long b = a + 1;
long res = 0;
if(Math.abs(Math.pow(a, 2) - n) > Math.abs(Math.pow(b, 2) - n)) res = (long)Math.pow(b, 2);
else res = (long)Math.pow(a, 2);
System.out.println(res);
}
}
分组
算法原理
暴力枚举,枚举每个组最多有多少人,根据这个人数算出每类可以分为多少个小组,当所有类型的小组和<=要求的组数时,就说明这个结果成立
代码
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static HashMap<Integer, Integer> map = new HashMap<>();
static int res = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int group = scan.nextInt();
int[] nums = new int[n];
int hmax = 0;
for (int i = 0; i < n; i++) {
nums[i] = scan.nextInt();
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
hmax = Math.max(hmax, map.get(nums[i]));
}
int kinds = map.size();
if (kinds > group) {
res = -1;
} else {
for (int i = 1; i <= hmax; i++) {
int sum = 0;
for (int x: map.values()) {
sum += x / i + (x % i == 0 ? 0 : 1);
}
if (sum <= group) {
res = i;
break;
}
}
}
System.out.println(res);
}
}
优化版
采用二分来优化寻找组的过程
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static HashMap<Integer, Integer> map = new HashMap<>();
static int res = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int group = scan.nextInt();
int[] nums = new int[n];
int hmax = 0;
for (int i = 0; i < n; i++) {
nums[i] = scan.nextInt();
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
hmax = Math.max(hmax, map.get(nums[i]));
}
int kinds = map.size();
if (kinds > group) {
res = -1;
} else {
int left = 1, right = hmax;
while(left < right) {
int mid = (left + right) / 2;
int sum = 0;
for(int x: map.values()) {
sum += x / mid + (x % mid == 0 ? 0 : 1);
}
if(sum <= group) right = mid;
else left = mid + 1;
}
res = left;
}
System.out.println(res);
}
}
拓扑排序
算法原理
拓扑排序模板
- 建图
- 找入度为0
- bfs
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
HashMap<Integer, List<Integer>> edges = new HashMap<>();
int[] in = new int[n + 1];
for (int i = 0; i < m; i++) {
int u = scan.nextInt();
int v = scan.nextInt();
if (!edges.containsKey(u))
edges.put(u, new ArrayList<>());
edges.get(u).add(v);
in[v]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 1; i <= n; i++) {
if (in[i] == 0) {
queue.offer(i);
}
}
int[] res = new int[n];
int index = 0;
while (!queue.isEmpty()) {
int u = queue.poll();
res[index++] = u;
for (int v : edges.getOrDefault(u, new ArrayList<>())) {
in[v]--;
if (in[v] == 0) {
queue.offer(v);
}
}
}
if (index != n) {
System.out.println(-1);
} else {
for (int i = 0; i < n; i++) {
System.out.print(res[i]);
if (i != n - 1) {
System.out.print(" ");
}
}
}
}
}