码迷,mamicode.com
首页 > 其他好文 > 详细

【HDOJ】1274 展开字符串

时间:2014-10-30 18:48:18      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   sp   div   on   

栈的应用,需要注意括号前可能没有数字的情况。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <iostream>
 5 #include <stack>
 6 #include <string>
 7 using namespace std;
 8 
 9 #define MAXN 300
10 #define isdigit(c) (c>=‘0‘ && c<=‘9‘)
11 #define islower(c) (c>=‘a‘ && c<=‘z‘)
12 char str[MAXN];
13 
14 void solve() {
15     string ans = "";
16     stack<char> ops;
17     stack<int> cnts;
18     stack<string> strs;
19     int cnt;
20     int i = 0;
21 
22     while (str[i]) {
23         bool found = false;
24         cnt = 0;
25         while (isdigit(str[i])) {
26             cnt = 10*cnt + str[i]-0;
27             ++i;
28             found = true;
29         }
30         if (str[i] == () {
31             if (!found)
32                 cnt = 1;
33             ops.push(();
34             cnts.push(cnt);
35             strs.push(ans);
36             ans = "";
37         } else if (str[i] == )) {
38             cnt = cnts.top();
39             cnts.pop();
40             ops.pop();
41             int r = cnt;
42             string bk = ans;
43             ans = strs.top();
44             strs.pop();
45             while (r) {
46                 if (r & 1)
47                     ans += bk;
48                 bk += bk;
49                 r >>= 1;
50             }
51         } else {
52             if (found) {
53                 string bk(cnt, str[i]);
54                 ans += bk;
55             } else {
56                 ans += str[i];
57             }
58         }
59         ++i;
60     }
61 
62     cout <<ans<<endl;
63 }
64 
65 int main() {
66     int t;
67 #ifndef ONLINE_JUDGE
68     freopen("data.in", "r", stdin);
69     freopen("data.out", "w", stdout);
70 #endif
71     scanf("%d", &t);
72     while (t--) {
73         scanf("%s", str);
74         solve();
75     }
76 
77     return 0;
78 }

 

【HDOJ】1274 展开字符串

标签:style   blog   io   color   os   ar   sp   div   on   

原文地址:http://www.cnblogs.com/bombe1013/p/4063227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!