poj1068Parencodings
括号的两种不同表示间的转换。
解题思路比较偷懒:先将括号恢复成我们喜欢看的形式,然后再转换成w型的表示方式。
代码
1import java.io.*;
2import java.util.*;
3class Main
4{
5 public static void main(String[] args)
6 {
7 Scanner sc = new Scanner(System.in);
8 int t = sc.nextInt();
9 for(int i = 0; i < t; i++)
10 {
11 int n = sc.nextInt();
12 int a = 0;
13 int b = 0;
14 StringBuffer strBuf = new StringBuffer();
15 for(int j = 0; j < n; j++)
16 {
17 b = sc.nextInt();
18 for(int k = 0; k < b - a; k++)
19 {
20 strBuf.append('(');
21 }
22 strBuf.append(')');
23 a = b;
24 }
25 boolean first = true;
26 for(int j = 0; j < strBuf.length(); j++)
27 {
28 if(strBuf.charAt(j) == ')')
29 {
30 int bi = getW(strBuf, j);
31 if(first)
32 {
33 System.out.print(bi);
34 first = false;
35 }
36 else
37 {
38 System.out.print(" " + bi);
39 }
40 }
41 }
42 System.out.println();
43 }
44 }
45 private static int getW(StringBuffer buf, int p)
46 {
47 int count = 0;
48 int right = 1;
49 for(int i = p - 1; i >= 0; i--)
50 {
51 if(buf.charAt(i) == ')')
52 {
53 right++;
54 }
55 else if(buf.charAt(i) == '(')
56 {
57 count++;
58 if(right == 1)
59 return count;
60 right--;
61 }
62 }
63 return -1;
64 }
65}
66
1import java.io.*;
2import java.util.*;
3class Main
4{
5 public static void main(String[] args)
6 {
7 Scanner sc = new Scanner(System.in);
8 int t = sc.nextInt();
9 for(int i = 0; i < t; i++)
10 {
11 int n = sc.nextInt();
12 int a = 0;
13 int b = 0;
14 StringBuffer strBuf = new StringBuffer();
15 for(int j = 0; j < n; j++)
16 {
17 b = sc.nextInt();
18 for(int k = 0; k < b - a; k++)
19 {
20 strBuf.append('(');
21 }
22 strBuf.append(')');
23 a = b;
24 }
25 boolean first = true;
26 for(int j = 0; j < strBuf.length(); j++)
27 {
28 if(strBuf.charAt(j) == ')')
29 {
30 int bi = getW(strBuf, j);
31 if(first)
32 {
33 System.out.print(bi);
34 first = false;
35 }
36 else
37 {
38 System.out.print(" " + bi);
39 }
40 }
41 }
42 System.out.println();
43 }
44 }
45 private static int getW(StringBuffer buf, int p)
46 {
47 int count = 0;
48 int right = 1;
49 for(int i = p - 1; i >= 0; i--)
50 {
51 if(buf.charAt(i) == ')')
52 {
53 right++;
54 }
55 else if(buf.charAt(i) == '(')
56 {
57 count++;
58 if(right == 1)
59 return count;
60 right--;
61 }
62 }
63 return -1;
64 }
65}
66