#include #include #include #include #include #include #include #include #include #include using namespace std; struct Lex { const char* str; Lex(const char* s) : str(s) {} string nextToken() { for(; *str; ++str) { if(*str == '{') { ++str; return "{"; } if(*str == '}') { ++str; return "}"; } if(islower(*str)) { string t; for(; isalpha(*str); ++str) t.push_back(*str); assert(t.size() <= 16); return t; } } return ""; } }; map env; struct Scope { set belong; multiset > name; Scope* parent; bool implicit; vector child; Scope(Scope* p = 0, bool impl = false) : parent(p), implicit(impl) {} void add(const string& token) { map::iterator i = env.find(token); if(i == env.end()) { env[token] = 1; belong.insert(token); } else ++i->second; } Scope* close() { for(int i = 0; i < (int)child.size(); ++i) { if(name.size() < child[i].name.size()) swap(name, child[i].name); vector tmp; for(multiset::iterator j = child[i].name.begin(); j != child[i].name.end(); ++j) { tmp.push_back(*name.begin() + *j); name.erase(name.begin()); } for(int i = 0; i < (int)tmp.size(); ++i) name.insert(tmp[i]); } for(set::iterator i = belong.begin(); i != belong.end(); ++i) { name.insert(env[*i]); env.erase(*i); } if(implicit) return parent->close(); return parent; } }; int main() { int n_line; ifstream cin("F.txt"); while(cin >> n_line && n_line) { assert(env.empty()); Scope global; Scope* cur = &global; int length = 0; string line; getline(cin, line); for(int i = 0; i < n_line; ++i) { getline(cin, line); length += count_if(line.begin(), line.end(), not1(ptr_fun(static_cast(&isspace)))); Lex lex(line.c_str()); for(string token = lex.nextToken(); !token.empty(); token = lex.nextToken()) { if(token == "{") { cur->child.push_back(Scope(cur)); cur = &cur->child.back(); } else if(token == "}") { cur = cur->close(); assert(cur); cur->child.push_back(Scope(cur, true)); cur = &cur->child.back(); } else { length -= token.size(); cur->add(token); } } } cur = cur->close(); //assert(cur == 0); int diff = 0; int len = 1; int cnt = 0; for(multiset::iterator i = global.name.begin(); i != global.name.end(); ++i) { //cout << *i << " -> " << len << endl; diff += len * *i; if(++cnt >= (1<