问题描述
代码实现
package com.gxwz.lanqiaobei;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* 试题G:外卖店优先级
* @author com
*/
public class TakeawayPriority {
// 先将数据存入二维数组 M=6 N=2 T=6
static Scanner sc = new Scanner(System.in);
static int N = sc.nextInt(); // N家外卖店
static int M = sc.nextInt(); // M行数据
static int T = sc.nextInt(); // T时刻
static int[][] A = new int[M][2]; // 保存输入的数据
static int[][] B = new int[T+1][N+1]; // 模拟N个外卖店T个时刻内的优先级
static List<Integer> list;
static Map<Integer, List<Integer>> map;
public static void main(String[] args) {
input(); // 输入
sort(); // 排序
// show(A);
tomap(); // map转存
core(); // 模拟外卖
// show(B);
System.out.println(result(T));
}
public static int result(int t) {
int n = 0;
for(int i=1;i<N+1;i++) {
if(B[t][i] != 0) {
n++;
}
}
return n;
}
public static void tomap() {
map = new HashMap<Integer, List<Integer>>();
List<Integer> list;
for(int i=0;i<M;i++) {
list = new ArrayList<Integer>();
list.add(A[i][1]);
while(i+1<M && A[i][0] == A[i+1][0]) {
list.add(A[++i][1]);
}
map.put(A[i][0], list);
}
// for (Entry<Integer, List<Integer>> entry : map.entrySet()) {
// System.out.println(entry.getKey()+" "+entry.getValue());
// }
}
public static void core() {
// map转二维数组B[T][N],模拟N个外卖店T个时刻内的优先级
for(int i=1;i<T+1;i++) {
for(int j=1;j<N+1;j++) {
if(map.containsKey(i)) {
list = map.get(i);
for(int k=0;k<list.size();k++) {
int n = list.get(k);
if(n == j) {
if(B[i][j] == 0) {
B[i][j] = B[i-1][j] + 2;
}else {
B[i][j] += 2;
}
}else if(B[i-1][j] != 0){
B[i][j] = B[i-1][j] - 1;
}
}
}if(B[i][j]==0 && B[i-1][j] != 0){
B[i][j] = B[i-1][j] - 1;
}
}
}
}
public static void input() {
for(int i=0;i<M;i++) {
A[i][0] = sc.nextInt();
A[i][1] = sc.nextInt();
}sc.close();
}
public static void sort() {
int length = A.length;
int t1,t2;
boolean flag;
while(length>0) {
flag = false;
for(int j=0;j<length-1;j++) {
if(A[j][0] > A[j+1][0]) {
// 交换第一个数
t1 = A[j][0];
A[j][0] = A[j+1][0];
A[j+1][0] = t1;
// 交换第二个数
t2 = A[j][1];
A[j][1] = A[j+1][1];
A[j+1][1] = t2;
flag = true;
}
}
if(!flag) break;
length--;
}
}
public static void show(int[][] A) {
for (int[] is : A) {
for (int i : is) {
System.out.print(i+" ");
}System.out.println();
}
}
}
运行结果
2