输入
5
8 6
10 8
6 0
20 8
2 6
8
输出
2 6
思路:没有用到算法,用HashMap来存 父目录:父目录下的所有子目录 即可。例如0:6
6:8、2
8:10、20
用List存放所有的目录,有0、6、8、2、10、20
要删的目录是8,遍历Hashmap,只要存在key是8的,先将List中的8删掉,再读Haspmap对应的value在List中对应删掉如10、20删掉,
然后要删的目录10.20..(目的是把他们的子目录也删掉),继续遍历Hashmap......
当然这是本人解法并非最优,【数组标记】
public class Directory删除 {
static List<Integer> res = new ArrayList();
static Map<Integer, List<Integer>> map = new HashMap();
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++) {
String[] s = sc.nextLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
if (!map.containsKey(b)) {
List l = new ArrayList<>();
l.add(a);
map.put(b, l);
if (!res.contains(a)) {
res.add(a);
}
if (!res.contains(b)) {
res.add(b);
}
} else {
List l = map.get(b);
l.add(a);
map.put(b, l);
if (!res.contains(a)) {
res.add(a);
}
}
}
int delete = sc.nextInt();
cal(delete);
Collections.sort(res);
for (int i : res) {
if (i == 0) {
continue;
}
System.out.print(i + " ");
}
}
static void cal(int delete) {
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
if (delete == entry.getKey()) {
if (res.contains(delete)) {
for (int i = 0; i < res.size(); i++) {
if (res.get(i) == delete) {
res.remove(i);
}
}
}
List<Integer> temp = entry.getValue();
for (int child : temp) {
if (res.contains(child)) {
for (int i = 0; i < res.size(); i++) {
if (res.get(i) == child) {
res.remove(i);
}
}
}
cal(child);
}
}
}
}
}