結果
問題 |
No.2427 Tree Distance Two
|
ユーザー |
|
提出日時 | 2023-11-09 19:44:40 |
言語 | Java (openjdk 23) |
結果 |
MLE
|
実行時間 | - |
コード長 | 2,845 bytes |
コンパイル時間 | 2,328 ms |
コンパイル使用メモリ | 81,664 KB |
実行使用メモリ | 768,620 KB |
最終ジャッジ日時 | 2024-09-26 00:32:28 |
合計ジャッジ時間 | 21,770 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 15 MLE * 20 |
ソースコード
import java.util.*; //無向グラフクラスを使うと、TLEした。 public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] edgeCounts = new int[n+1]; int[][] list = new int[n+1][n+1]; int[] cnt = new int[n+1]; for (int i = 0 ; i < n - 1; i++){ int u = sc.nextInt(); int v = sc.nextInt(); list[u][cnt[u]] = v; cnt[u]++; list[v][cnt[v]] = u; cnt[v]++; edgeCounts[u]++; edgeCounts[v]++; } sc.close(); StringBuilder sb = new StringBuilder(); for(int i = 1 ; i <= n ; i++){ int edgeSum = 0; //頂点iがつながっている(隣接する)各頂点がもつ、辺の数を調べ、合計(edgeSum)をとる。 for(int to : list[i]){ if(to == 0){ continue; } edgeSum += edgeCounts[to]; } //頂点iがもつ辺の数と、辺の数の合計(edgeSum)を引く。 sb.append(edgeSum - edgeCounts[i]+"\n"); } System.out.print(sb); } } //グラフのエッジ(辺)を格納するクラス class Edge { public int from, to; /**コンストラクタ * @param : from 頂点 * @param : to つながっている頂点 */ Edge(int from, int to) { this.from = from; this.to = to; } public int getFrom(){ return from; } public int getTo(){ return to; } public void setFrom(int from){ this.from = from; } public void setTo(int to){ this.to = to; } } //無向グラフクラス class Graph { //隣接リストを表すリストのリスト(ある頂点が、どの頂点とつながっているかを保持するリスト) Map<Integer , List<Edge>> edgeMap = new HashMap<>(); /**コンストラクタ * @param edges : 辺 * @param n : 頂点の個数 * */ public Graph(int n) { for (int i = 0; i < n; i++) { edgeMap.put(i ,new ArrayList<>()); } } public void addEdge(Edge edge){ int from = edge.getFrom(); int to = edge.getTo(); List<Edge> tmp1 = edgeMap.get(from); tmp1.add(edge); edgeMap.put(from , tmp1); List<Edge> tmp2 = edgeMap.get(to); Edge tmpEdge = new Edge(to , from); tmp2.add(tmpEdge); edgeMap.put(to , tmp2); } public int size() { return edgeMap.size(); } public List<Edge> getEdgsList(int vNum) { return edgeMap.get(vNum); } }