您的位置:首页 > 其它

题目1090:路径打印

2014-01-08 21:52 232 查看
/*
题目描述:

给你一串路径,譬如:
a\b\c
a\d\e
b\cst
d\
你把这些路径中蕴含的目录结构给画出来,子目录直接列在父目录下面,并比父目录向右缩一格,就像这样:
a
b
c
d
e
b
cst
d
同一级的需要按字母顺序排列,不能乱。

输入:

每个测试案例第一行为一个正整数n(n<=10)表示有n个路径,当n为0时,测试结束,接下来有n行,每行有一个字串表示一个路径,长度小于50。

输出:

输出目录结构,每一个测试样例的输出紧跟一个空行。

样例输入:

4
a\b\c
a\d\e
b\cst
d\
0

样例输出:

a
b
c
d
e
b
cst
d

*/
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;

class Node
{
private static final int N = 100;

public int n;
public int[] next;
public int id;
public String s;

Node()
{
n = 0;
next = new int
;
}
}

class Main
{
public static final boolean DEBUG = false;
private static final int  N = 10000;
private int top;
public Node[] node;
public Comparator comp;

private void init()
{
top = 1;
node = new Node
;

for (int i = 0; i < N; i++) {
node[i] = new Node();
}

comp = new Comparator<Node>() {
public int compare(Node a, Node b) {

if (a.s.compareTo(b.s) < 0) return -1;
else if (a.s.compareTo(b.s) == 0) return 0;

return 1;
}
};

}

public void dfs(int cur, int dep)
{
if (node[cur].n == 0) return;

Node[] tmp = new Node[node[cur].n];
for (int i = 0; i < node[cur].n; i++) {
tmp[i] = node[node[cur].next[i]];
}

Arrays.sort(tmp, comp);

for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < dep; j++) {
System.out.print(" ");
}

System.out.println(tmp[i].s);

dfs(tmp[i].id, dep + 1 + tmp[i].s.length());
}
}

public void insert(String s)
{
int p = 0, n;
int cur = 0;

boolean stop = false;
while (!stop) {
n = s.indexOf('\\', p);
String tmp;

if (n == -1) {
stop = true;
tmp = s.substring(p, s.length());
} else
tmp = s.substring(p, n);
p = n + 1;

boolean flag = true;

if (tmp.compareTo("") != 0)
for (int i = 0; i < node[cur].n; i++) {
int label = node[cur].next[i];
if (tmp.compareTo(node[label].s) == 0) {
flag = false;
cur = label;
break;
}
}

if (flag && tmp.compareTo("") != 0) {
node[cur].next[node[cur].n++] = top;
node[top].s = tmp;
node[top].id = top;
cur = top++;
}
}
}

public static void main(String[] args) throws IOException
{
Scanner cin;
int n;
String s;

if (DEBUG) {
cin = new Scanner(new BufferedReader(new FileReader("d:\\OJ\\uva_in.txt")));
} else {
cin = new Scanner(System.in);
}

Main solve = new Main();
while (cin.hasNext()) {
n = cin.nextInt();
if (n == 0) break;

solve.init();
for (int i = 0; i < n; i++) {
s = cin.next();
solve.insert(s);
}
solve.dfs(0, 0);

System.out.println();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: