POJ1068(ACM括號模擬)
阿新 • • 發佈:2018-12-24
Description
Let S = s1 s2...s2n be a well-formed string of parentheses. S can be encoded in two different ways:q By an integer sequence P = p1 p2...pn where pi is the number of left parentheses before the ith right parenthesis in S (P-sequence).
q By an integer sequence W = w1 w2...wn where for each right parenthesis, say a in S, we associate an integer which is the number of right parentheses counting from the matched left parenthesis of a up to a. (W-sequence).
Following is an example of the above encodings:
S (((()()()))) P-sequence 4 5 6666 W-sequence 1 1 1456
Write a program to convert P-sequence of a well-formed string to the W-sequence of the same string.
Input
The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case is an integer n (1 <= n <= 20), and the second line is the P-sequence of a well-formed string. It contains n positive integers, separated with blanks, representing the P-sequence.Output
Sample Input
2 6 4 5 6 6 6 6 9 4 6 6 6 6 8 9 9 9
Sample Output
1 1 1 4 5 6 1 1 2 4 5 1 1 3 9
Source
先根據P陣列,將括號陣列進行還原。再遍歷括號陣列,給每個右括號確定自己對應的左括號,並統計M陣列的值。
程式碼:
import java.util.Scanner;
//poj1068:括號問題(ACM模擬)
public class Main {
static int[] data_P;// P陣列
static int[] data_W;// W陣列
static char[] data;// 括號陣列
static int[] flag;// 左括號標記陣列
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int casenum = in.nextInt();// 所有case的數量
int[] len = new int[casenum];
int[][] case_P = new int[casenum][];
for (int num = 0; num < casenum; num++) {
int ind = in.nextInt();// W陣列的長度
len[num] = ind;
int[] per_P = new int[ind + 1];// P陣列長度多1。
for (int i = 1; i < per_P.length; i++) {
per_P[i] = in.nextInt();
}
case_P[num] = per_P;
}
for (int i = 0; i < casenum; i++) {
// 初始化各陣列
int inx = len[i];
data_P = case_P[i];
data_W = new int[inx];
data = new char[2 * inx];// 括號陣列長度為2倍
flag = new int[2 * inx];// 對應括號陣列
// 呼叫還原括號陣列的函式
theBracket(0);
System.out.println();
}
}
// 還原括號陣列--index:陣列遊標
public static void theBracket(int index) {
for (int i = 1; i < data_P.length; i++) {
int temp = data_P[i] - data_P[i - 1];
for (int j = 0; j < temp; j++) {// 該右括號與上一個右括號之間左括號的數量
data[index] = '(';
index++;
}
// 還原完左括號最後還原一個右括號
data[index++] = ')';
}
printdata_W();
}
// 計算W陣列
public static void printdata_W() {
int indd = 0;// W陣列遊標
for (int i = 0; i < data.length; i++) {
int count = 0;// W陣列某位置的值
// 如果找到一個右括號,就以此為起點,回溯到0;期間遇到一個右括號,count+1;
// 遇到一個括號且標誌位不為0,將該標誌位置1;break將count值放到W陣列中,繼續向後找。
if (data[i] == ')') {
for (int j = i; j >= 0; j--) {
if (data[j] == ')') {
count++;
}
if (data[j] == '(' && flag[j] == 0) {
flag[j] = 1;
break;
}
}
data_W[indd++] = count;
}
}
// 輸出W陣列
for (int i = 0; i < data_W.length; i++) {
if (i == data_W.length - 1) {
System.out.print(data_W[i]);
} else {
System.out.print(data_W[i] + " ");
}
}
}
}