生活随笔
收集整理的這篇文章主要介紹了
CH1801
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
括號畫家
Candela是一名漫畫家,她有一個奇特的愛好,就是在紙上畫括號。這一天,剛剛起床的Candela畫了一排括號序列,其中包含小括號()、中括號[]和大括號{},總長度為N。這排隨意繪制的括號序列顯得雜亂無章,于是Candela定義了什么樣的括號序列是美觀的:
(1) 空的括號序列是美觀的;
(2) 若括號序列A是美觀的,則括號序列(A)、[A]、{A}也是美觀的;
(3) 若括號序列A、B都是美觀的,則括號序列AB也是美觀的;
例如 (){} 是美觀的括號序列,而 )({)[}]( 則不是。
現在Candela想在她繪制的括號序列中,找出其中連續的一段,滿足這段子序列是美觀的,并且長度盡量大。你能幫幫她嗎?
輸入:
第一行1個整數N,第二行1個長度為N的括號序列。
各個測試點的N的大小:5,10,50,100,100,1000,1000,10000,10000,10000
輸出:
一個整數,表示最長的美觀的連續子序列的長度。
思路:
人都給我做傻了,搞了一上午。。。
大概就是保存上一個失敗的位置,每次匹配成功就算一下這次用了多少字符,大概就是這樣
對于代碼:
中間有好長一節是用來測試的,tans是標準答案,ans是我算出來的答案,如果不一樣我就輸出一系列信息,如果最后沒有輸出說明代碼是對的。調試的時候把數據文件復制到文件夾就行了,很方便的。
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>#define INF 0x3f3f3f3f
#define IMAX 2147483646
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned intusing namespace std
;int s
, n
,ans
;
char str
[11111], st
[11111];
int sta
[11111];int main() {int t
= 12;while (t
--) {char iname
[555] = "";char oname
[555] = "";sprintf(iname
, "sequence%d.in", t
+1);sprintf(oname
, "sequence%d.out", t
+1);freopen(iname
, "r", stdin);scanf("%s", str
);n
= strlen(str
);ans
= 0;s
= 1;sta
[0] = -1;st
[0] = '9';for (int i
= 0; i
< n
; i
++) {if (str
[i
] == ')'||str
[i
] == '}'||str
[i
]==']') {if (s
!= 1 && ((str
[i
] == ')'&&st
[s
- 1] == '(')|| (str
[i
] == ']'&&st
[s
- 1] == '[')|| (str
[i
] == '}'&&st
[s
- 1] == '{'))) {s
--;ans
= max(ans
, i
- sta
[s
- 1]);}else {while (s
> 1)s
--;sta
[0] = i
;}continue;}sta
[s
] = i
;st
[s
++] = str
[i
];}FILE
*fp
= fopen(oname
, "r");int tans
= 0;fscanf(fp
, "%d", &tans
);fclose(fp
);if (tans
!= ans
) printf("case:%d: %s\n %d %d\n",t
+1, str
, tans
, ans
);}return 0;
}
總結
以上是生活随笔為你收集整理的CH1801的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。