注意,lz并没有参加在线笔试,只是拿来练习一下,由于在hihocoder上并不能提交,只能用样例测试,所以不保证答案完全正确
题目:http://hihocoder.com/contest/ntest2015septdev/problem/2
分析:模拟题,递归降解即可,最坏复杂度为O(N^2),串的长度不超过100,所以复杂度可以接受
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
const char* FindMatchedRight(const char* p)
{
int left = 1;
for(++p; ; ++p){
if(*p == '(') ++left;
else if(*p == ')' && !--left) break;
}
return p;
}
int GetOriginalLength(const string& s)
{
int tot = 0;
const char *t = s.c_str(), *p = t, *q;
for(; *p; p = q){
if(isupper(*p)){//*p = 'X'
q = p + 1;
if(!isdigit(*q)) ++tot;
else{//it is like X123 here
for(++q; isdigit(*q); ++q) ;
//now *q is not a digit
tot += atoi(p + 1);
}
}
else{//*p = '(', it is like (ABC)123 here
q = FindMatchedRight(p);
//*q = ')' now, find out patten length
int patlen = GetOriginalLength(s.substr(p + 1 - t, q - p - 1));
//find out the repeats of the patten
const char* h = q+1;//h points to the first digit now
for(q = h+1; isdigit(*q); ++q) ;
tot += patlen * atoi(h);
}
}
return tot;
}
int main()
{
int test;
string s;
for(cin >> test; test--; ){
cin >> s;
cout << GetOriginalLength(s) << "\n";
}
return 0;
}