题解分享
题解分享简介
分布式队列(编程题) - 题解
视频中的标准程序代码如下:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = 15;
int[] pos = new int[N];
int n = scanner.nextInt();
scanner.nextLine(); // consume the newline character after n
while (scanner.hasNext()) {
String x = scanner.next();
if (x.equals("add")) {
int y = scanner.nextInt();
pos[0]++;
} else if (x.equals("sync")) {
int y = scanner.nextInt();
pos[y]++;
pos[y] = Math.min(pos[y], pos[0]);
} else if (x.equals("query")) {
int ans = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) ans = Math.min(ans, pos[j]);
System.out.println(ans);
}
}
scanner.close();
}
}
```
查看全文
3
0
1
10
分布式队列(编程题) - 题解
我的思路是,a[0]表示"主队列"的元素个数,a[1~n]对应"从队列"的元素个数,收到指令add就主队列++,收到指令sync就从队列++,这个时候数组a[n]的最小值就是队列元素的可见性。
```
import java.util.Scanner;
public class Main {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int n=sc.nextInt();
sc.nextLine();
int[] a = new int[n];
String cmd,num;
int min;
while(sc.hasNext()) {
cmd = sc.nextLine();
if(cmd.charAt(0)=='a') {
a[0]++;
}else if(cmd.charAt(0)=='s') {
num = "";
for(int i=5;i<cmd.length();i++) {
if(cmd.charAt(i)>='0'&&cmd.charAt(i)<='9') //站长给的测评数据数字后面有空格只好筛掉了
num+=cmd.charAt(i);
}
a[Integer.parseInt(num)]++;
}else if(cmd.charAt(0)=='q') {
min = Integer.MAX_VALUE;
for(int j=0;j<a.length;j++) {
min = Math.min(min,a[j]);
}
System.out.println(min);
}
}
}
}
```
查看全文
1
0
0
6



