2761956 | 2008-02-26 19:16:05 | Accepted | 2704 | C++ | 00:00.14 | 924K | C.D.=.= |
犯了一个极其低级的错误,把l = strlen(str); for ( i = 0; i < l; i ++ )写成了for ( i = 0; i < strlen ( str ); i ++ ),结果超时无数次。当for循环足够大时,不起眼的地方积累起来,错误也会变得很显著。起初想到可能是使用STL导致的超时,于是把栈简单模拟,结果仍然。看来对这种地方还是不够敏感啊。
1
#include <cstdio>
2
#include <string>
3
4
char str[100001];
5
int s[100001], top;
6
7
void pt ();
8
void print ( int, int );
9
10
int main ()
11

{
12
// '(' -1 ')' -2 '[' -3 ']' -4
13
//freopen ( "in.txt", "r", stdin );
14
while ( scanf ( "%s", str ) != EOF )
15
{
16
top = -1;
17
s[++ top] = -5;
18
int i, sum, ans = 0, pos, l = strlen ( str );
19
for ( i = 0; i < l; i ++ )
20
{
21
sum = 0;
22
if ( s[top] > 0 )
23
{
24
sum = s[top];
25
top --;
26
}
27
if ( str[i] == '(' )
28
{
29
if ( sum )
30
s[++ top] = sum;
31
s[++ top] = -1;
32
}
33
else if ( str[i] == '[' )
34
{
35
if ( sum )
36
s[++ top] = sum;
37
s[++ top] = -3;
38
}
39
else if ( str[i] == ')' )
40
{
41
if ( s[top] == -1 )
42
{
43
top --;
44
sum += 2;
45
if ( s[top] > 0 )
46
{
47
sum += s[top];
48
top --;
49
}
50
s[++ top] = sum;
51
}
52
else
53
{
54
if ( sum )
55
s[++ top] = sum;
56
s[++ top] = -2;
57
}
58
}
59
else if ( str[i] == ']' )
60
{
61
if ( s[top] == -3 )
62
{
63
top --;
64
sum += 2;
65
if ( s[top] > 0 )
66
{
67
sum += s[top];
68
top --;
69
}
70
s[++ top] = sum;
71
}
72
else
73
{
74
if ( sum )
75
s[++ top] = sum;
76
s[++ top] = -4;
77
}
78
}
79
sum = 0;
80
if ( s[top] > 0 )
81
{
82
sum += s[top];
83
top --;
84
}
85
if ( sum )
86
s[++ top] = sum;
87
if ( ans < sum )
88
pos = i - sum + 1, ans = sum;
89
//pt ();
90
}
91
print ( pos, ans );
92
}
93
return 0;
94
}
95
96
void print ( int pos, int ans )
97

{
98
int i;
99
for ( i = 0; i < ans; i ++ )
100
printf ( "%c", str[i + pos] );
101
printf ( "\n\n" );
102
}
103
104
105

2

3

4

5

6

7

8

9

10

11



12

13

14

15



16

17

18

19

20



21

22

23



24

25

26

27

28



29

30

31

32

33

34



35

36

37

38

39

40



41

42



43

44

45

46



47

48

49

50

51

52

53



54

55

56

57

58

59

60



61

62



63

64

65

66



67

68

69

70

71

72

73



74

75

76

77

78

79

80

81



82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97



98

99

100

101

102

103

104

105

评论