Java自定义排序
定义类,并且以需要关键字排序的方法
AcWing 5407. 管道
import java.util.*;
import java.io.*;
public class Main {
static final int N = 100010;
static int[][] g = new int[N][2];
static int n, m;
static class sg implements Comparable<sg>{
int x, y;
public sg(int x, int y)
{
this.x = x;
this.y = y;
}
public int compareTo(sg s)
{
if(x != s.x) return x - s.x; //以x为第一关键字从小到达排序
else return y - s.y;
}
}
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] s;
s = bf.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
int x = -1;
for(int i = 1; i <= n; i ++)
{
s = bf.readLine().split(" ");
g[i][0] = Integer.parseInt(s[0]);
g[i][1] = Integer.parseInt(s[1]);
x = Math.max(x, g[i][1]);
}
int l = 0, r = x + m;
while(l < r)
{
int mid = (int)((long)l + r >> 1);
if(check(mid)) r = mid;
else l = mid + 1;
}
bw.write("" + l);
bw.flush();
}
public static boolean check(int mid)
{
List<sg> k = new ArrayList<>();
for(int i = 1; i <= n; i ++)
{
int num = g[i][0];
int s = g[i][1];
if(mid >= s)
k.add(new sg(Math.max(num - mid + s, 1), Math.min(num + mid - s, m)));
}
if(k.size() == 0) return false;
Collections.sort(k); //排序函数
int r = 0;
for(sg p : k)
{
if(p.x > r + 1) return false;
r = Math.max(r, p.y);
}
if(r == m) return true;
return false;
}
}
Java数组降序排序的实现方法:
Java堆的初始化以及堆的自定义排序写法:1262. 鱼塘钓鱼
import java.util.*;
import java.io.*;
public class Main {
static final int N = 110, M = N * 10;
static int[] a = new int[N];
static int[] b = new int[N];
static int[] c = new int[N];
static class fish implements Comparable<fish>
{
int x, y;
public fish(int x, int y)
{
this.x = x;
this.y = y;
}
public int compareTo(fish t) //重载比较,这里要初始化位小根堆,堆写法与平时排序写法相反
{
return t.x - x;
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
//BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
//BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
for(int i = 1; i <= n; i ++)
{
a[i] = sc.nextInt();
}
for(int i = 1; i <= n; i ++)
{
b[i] = sc.nextInt();
}
for(int i = 1; i <= n - 1; i ++)
{
c[i] = sc.nextInt();
}
int T = sc.nextInt();
int res = 0;
int cnt = 0;
int u = T;
for(int i = 1; i <= n; i ++)
{
u = T;
cnt = 0;
for(int j = 1; j < i; j ++) u -= c[j];
if(u <= 0) break; //枚举需要走的鱼塘数量
Queue<fish> q = new PriorityQueue<>(); //定义堆
for(int k = 1; k <= i; k ++)
{
q.add(new fish(a[k], b[k]));
}
while(q.size() > 0) //定义循环退出条件
{
fish t = q.remove();
cnt += t.x;
u --;
if(u <= 0) break;
if(t.x - t.y > 0)
{
q.add(new fish(t.x - t.y, t.y));
}
}
res = Math.max(res, cnt);
}
System.out.println(res);
}
}