百練2010D: 括號描述問題

描述:
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.
輸入
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.
輸出
The output file consists of exactly t lines corresponding to test cases. For each test case, the output line should contain n integers describing the W-sequence of the string corresponding to its given P-sequence.
樣例輸入
2
6
4 5 6 6 6 6
9 
4 6 6 6 6 8 9 9 9
樣例輸出
1 1 1 4 5 6
1 1 2 4 5 1 1 3 9
 二:題意理解: 、題目中關於括號的兩種描述理解:對於長度爲2N的括號序列,兩個數組,其中P[i]表示就是對於數組中的右括號其左括號有多少個,而對於W[i]表示對每一個右括號而言,其對稱的左括號到該右括號時所經歷的左括號,其中包括這個右括號本身匹配的左括號;
②、結題的基本思想其實就是理解這兩個括號描述方法的差別,對將P[i]形式轉化爲W[i]形式而言,引入一個輔助數組B[i],它表示每一個右括號與前一個右括號之間所隔離的左括號的數目,顯然對於 i=0,B[i]=P[i],  此外,B[i] = P[i] - P[i-1];
③、計算W[i]的思想在代碼中有明顯體現,其實就是掃描 W[i] 和 B[i],當B[i]>0 時,說明 右括號 I 的左側還有左括號,顯然根據括號匹配的原則(最近原則),那麼W[i]爲1,此外匹配成功一次,要將Bi] -1; 當B[i] =0 時,那麼就要向前尋找最近個一個不爲0的B[k] 值,顯然要求k<i,W[i] = 1+ (i-k);


 三:源碼:
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int t, n;
	int i, j;
	int *B, *P, *W;
	
	scanf("%d", &t);
	while(t>0)
	{
		scanf("%d", &n);
		B = (int*)malloc(n*sizeof(int));
		P = (int*)malloc(n*sizeof(int));
		W = (int*)malloc(n*sizeof(int));
		
		for(i=0; i<n; i++)
		{
			scanf("%d", &P[i]);
			if(i==0)
				B[i] = P[i];
			else
				B[i] = P[i]-P[i-1];
		}
		
		for(i=0; i<n; i++)
		{
			if(B[i]>0)
			{
				W[i] = 1;
				B[i] --;
			}
			
			else
			{
				for(j=i-1; j>=0; j--)
				{
					if(B[j]>0)
					{
						W[i] = i-j+1;
						B[j]--;
						break;
					}
					else
						continue;
				}
			}
		}
		
		for(i=0; i<n; i++)
		{
			printf("%d ", W[i]);
			if(i == n-1)
				printf("\n");
		}
			
		free(B);
		free(P);
		free(W);
			
		t--;
	}
	
	system("pause");
	return 0;
}
					
			
			
			
			
			
			
			
			







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章