Time Limit: 8 sec / Memory Limit: 64 MB





Example

Input

100
A=malloc(10)
B=clone(A)
free(A)


Output

0
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cctype>
using namespace std;


struct memory{
	int size;
	int count;
	bool deleted;
	
	memory( int s, bool d )
		: size(s), count(0), deleted(d) {}
};

typedef list<memory>::iterator lmitr;


list<memory> memlist;
lmitr vars[26];
lmitr nullitr, undefitr;
vector<lmitr> allocated;	//新規確保されたメモリ(+α)

string input;
int pos;
int M;
int leak;


void error(){
	cout << "Error\n";
	exit(0);
}


lmitr malloc_( int num ){
	if( num <= M ){
		M -= num;
		lmitr ret = memlist.insert( memlist.end(), memory( num, false ) );
		allocated.push_back( ret );
		return ret;
	}
	return nullitr;
}

void free_( lmitr it ){
	if( it->deleted ){
		error();
	}

	if( it != nullitr ){
		M += it->size;
		it->deleted = true;
	}
}

lmitr clone( lmitr it ){
	if( it->deleted ){
		error();
	}
	
	if( M < it->size || it == nullitr ){
		return nullitr;
	}
	
	M -= it->size;
	lmitr ret = memlist.insert( memlist.end(), memory( it->size, false ) );
	allocated.push_back( ret );
	return ret;
}

void assign( int v, lmitr itr ){
	if( vars[v] != itr ){
		if( vars[v] != nullitr && vars[v] != undefitr ){
			--vars[v]->count;
			if( vars[v]->count == 0 ){
				allocated.push_back( vars[v] );		//GC待ち
			}
		}
		
		vars[v] = itr;
		++itr->count;
	}
}


lmitr expression(){
	if( isupper( input[pos] ) ){
		if( input[pos+1] == 'U' ){	//NULL
			pos += 4;
			return nullitr;
		}

		int v = input[pos] - 'A';
		++pos;
		if( input[pos] == '=' ){	//assignment
			++pos;
			lmitr ret = expression();
			assign( v, ret );
			return ret;
		}
		else{
			return vars[v];
		}
	}
	
	if( input[pos] == '(' ){
		++pos;	//(
		lmitr ret = expression();
		++pos;	//)
		return ret;
	}
	
	if( input[pos] == 'm' ){	//malloc(
		char *p;
		int size = strtol( input.c_str() + (pos + 7), &p, 10 );
		pos = p - input.c_str() + 1;	// )
		return malloc_( size );
	}
	
	if( input[pos] == 'c' ){	//clone(
		pos += 6;
		lmitr it = expression();
		++pos;	// )
		return clone( it );
	}
	
	abort();	//unexpected
}


void solve(){
	while( cin >> input ){
		pos = 0;
		
		if( input[0] == 'f' ){
			pos = 5;	//free(
			free_( expression() );
		}
		else{
			expression();
		}


		for( int j = 0; j < allocated.size(); ++j ){
			if( allocated[j]->count == 0 ){
				if( !allocated[j]->deleted ){
					leak += allocated[j]->size;
				}
				memlist.erase( allocated[j] );
			}
		}
		allocated.clear();
	}
	
	cout << leak << endl;
}


int main(){
	nullitr = memlist.insert( memlist.end(), memory( 0, false ) );
	undefitr = memlist.insert( memlist.end(), memory( 0, true ) );
	
	fill( vars, vars + 26, undefitr );
	
	cin >> M;
	solve();
}