1.使用数组保存节点之间相邻关系
2.使用List<Integer>数组维护每个节点的主链
3.使用优先队列保存更新的数据
import java.util.*;
/**
* 运行时间超时 分数为80
*/
public class Main{
static class Message implements Comparable<Message>{
int time;
int nodeId;
List<Integer> list;
//false表示需要比对,true表示直接添加
boolean dif;
public Message(int time, int nodeId, List<Integer> list, boolean dif) {
this.time = time;
this.nodeId = nodeId;
this.list = list;
this.dif = dif;
}
@Override
public String toString() {
return "Message{" +
"time=" + time +
", nodeId=" + nodeId +
", list=" + list +
", dif=" + dif +
'}';
}
@Override
public int compareTo(Message o) {
return this.time == o.time ? (this.dif ? 1 : -1) : this.time - o.time;
}
}
//节点数目
static int n;
//连接关系
static int[][] arr;
//传播时延
static int t;
/**
* 每个节点维护一条主链,主链初始值为0,长度为1
*/
static List<Integer>[] nodeList;
//消息队列
static PriorityQueue<Message> queue;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
n = input.nextInt();
int m = input.nextInt();
arr = new int[n + 1][n + 1];
for (int i = 0; i < m; i++){
int a = input.nextInt();
int b = input.nextInt();
arr[a][b] = 1;
arr[b][a] = 1;
}
t = input.nextInt();
int len = input.nextInt();
input.nextLine();
nodeList = new List[n + 1];
for (int i = 1; i <= n; i++){
List<Integer> cur = new ArrayList<>();
cur.add(0);
nodeList[i] = cur;
}
queue = new PriorityQueue<>();
for (int i = 0; i < len; i++){
String str = input.nextLine();
String[] strs = str.split(" ");
if (strs.length == 3){
List<Integer> cur = new ArrayList<>();
cur.add(Integer.parseInt(strs[2]));
queue.offer(new Message(Integer.parseInt(strs[1]), Integer.parseInt(strs[0]), cur, true));
//System.out.println(queue);
} else {
deal(Integer.parseInt(strs[1]));
print(Integer.parseInt(strs[0]));
}
}
input.close();
}
/**
* 处理数据,将time时刻及其之前时间的数据处理完毕
* @param time 查询的当前时刻
*/
public static void deal(int time){
while (!queue.isEmpty() && queue.peek().time <= time){
Message mes = queue.poll();
update(mes);
}
}
/**
* 根据消息队列进行数据更新
* @param mes
*/
public static void update(Message mes){
//如果为true,直接添加节点,否之,比对
List<Integer> newList;
if (mes.dif){
nodeList[mes.nodeId].add(mes.list.get(0));
} else {
//1.比较两者大小
List<Integer> source = nodeList[mes.nodeId];
newList = mes.list;
int oldSize = source.size();
int newSize = newList.size();
if (oldSize > newSize || (oldSize == newSize && source.get(oldSize - 1) <= newList.get(oldSize - 1))){
return;
}
nodeList[mes.nodeId] = newList;
}
for (int i = 1; i <= n; i++){
if (arr[mes.nodeId][i] == 1){
queue.offer(new Message(mes.time + t, i, new ArrayList<>(nodeList[mes.nodeId]), false));
}
}
}
public static void print(int nodeId){
List<Integer> list = nodeList[nodeId];
System.out.print(list.size() + " ");
for (int i : list){
System.out.print(i + " ");
}
System.out.println();
}
}
代码问题颇多,欢迎提出各种建议