2018年第九屆藍橋杯Java程序設計本科B組決賽個人題解彙總:
https://blog.csdn.net/daixinliangwyx/article/details/90258768
第四題
標題:版本分支
小明負責維護公司一個奇怪的項目。這個項目的代碼一直在不斷分支(branch)但是從未發生過合併(merge)。
現在這個項目的代碼一共有N個版本,編號1~N,其中1號版本是最初的版本。
除了1號版本之外,其他版本的代碼都恰好有一個直接的父版本;即這N個版本形成了一棵以1爲根的樹形結構。
如下圖就是一個可能的版本樹:
1
/ \
2 3
| / \
5 4 6
現在小明需要經常檢查版本x是不是版本y的祖先版本。你能幫助小明嗎?
輸入
----
第一行包含兩個整數N和Q,代表版本總數和查詢總數。
以下N-1行,每行包含2個整數u和v,代表版本u是版本v的直接父版本。
再之後Q行,每行包含2個整數x和y,代表詢問版本x是不是版本y的祖先版本。
對於30%的數據,1 <= N <= 1000 1 <= Q <= 1000
對於100%的數據,1 <= N <= 100000 1 <= Q <= 100000
輸出
----
對於每個詢問,輸出YES或NO代表x是否是y的祖先。
【樣例輸入】
6 5
1 2
1 3
2 5
3 6
3 4
1 1
1 4
2 6
5 2
6 4
【樣例輸出】
YES
YES
NO
NO
NO
資源約定:
峯值內存消耗(含虛擬機) < 256M
CPU消耗 < 1000ms
請嚴格按要求輸出,不要畫蛇添足地打印類似:“請您輸入...” 的多餘內容。
所有代碼放在同一個源文件中,調試通過後,拷貝提交該源碼。
不要使用package語句。不要使用jdk1.7及以上版本的特性。
主類的名字必須是:Main,否則按無效代碼處理。
解法:每次詢問都進行遞歸查找肯定是會超時的。想到一種比較好的方法就是,因爲已經知道根結點就是1號點了,所以可以從1號點開始就遞歸把當前層結點的下一層結點的孩子集合合併在一塊返回給當前層結點,進行一輪遞歸就完成了,然後就可以在每次詢問裏O(1)查找x的孩子集合裏面是否包含y。
代碼:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class MainB {
public static InputReader in = new InputReader(new BufferedInputStream(System.in));
public static PrintWriter out = new PrintWriter(System.out);
public static int n, q, u, v, x, y;
public static ArrayList<Integer>[] child = new ArrayList[100010];
public static ArrayList<Integer>[] next = new ArrayList[100010];
public static void main(String[] args) {
n = in.nextInt();
q = in.nextInt();
for (int i = 1; i <= n; i++) {
next[i] = new ArrayList<>();
child[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
u = in.nextInt();
v = in.nextInt();
next[u].add(v);
}
child[1] = getChild(1);
while (q-- > 0) {
x =in.nextInt();
y = in.nextInt();
if (child[x].contains(y)) {
out.println("YES");
out.flush();
} else {
out.println("NO");
out.flush();
}
}
out.close();
}
static ArrayList<Integer> getChild(int root) {
int len = next[root].size();
for (int i = 0; i < len; i++)
child[root].addAll(getChild(next[root].get(i)));
child[root].add(root);
return child[root];
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
}