图论题,建图后求所有无父节点的点,直接DFS,在搜索过程中将有父节点的点标记下,最后没标记过的点就是所有的源点,排下序就结束了。。话说感觉效率好低啊,这题本来挺简单的,还是写了近一个小时,脑子好迟钝的感觉,不知道是不是因为下午犯困的原因。。还好一次A了,不然找BUG就坑惨了,脑子完全转不动了
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Main
{
static Map<String, Boolean> parent = new HashMap<String, Boolean>();
static Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
static Set<String> visit = new HashSet<String>();
static ArrayList<String> result = new ArrayList<String>();
static void dfs(String name)
{
visit.add(name);
if (map.containsKey(name))
{
for (String adj : map.get(name))
{
parent.put(adj, true);
if (!visit.contains(adj))
dfs(adj);
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
boolean first = true;
while (sc.hasNext())
{
if (!first)
System.out.println();
if (first)
first = false;
parent.clear();
map.clear();
visit.clear();
result.clear();
String line = sc.nextLine();
int n = Integer.parseInt(line);
while (n-- > 0)
{
line = sc.nextLine();
parent.put(line, false);
if (!map.containsKey(line))
map.put(line, new ArrayList<String>());
String ss[] = sc.nextLine().split(" ");
for (int i = 1; i < ss.length; i++)
{
parent.put(ss[i].trim(), false);
map.get(line).add(ss[i].trim());
}
}
for (String key : map.keySet())
if (!visit.contains(key))
dfs(key);
for (String key : parent.keySet())
if (!parent.get(key))
result.add(key);
Collections.sort(result);
for (String s : result)
System.out.println(s);
}
sc.close();
}
}