/* FILE: editFormulaDP.cpp last change: 1-Jul-2013 author: Romeo Rizzi * a solver for problem editFormula based on dynamic programming */ #define NDEBUG // NDEBUG definita nella versione che consegno #include #ifndef NDEBUG # include // uso di cin e cout non consentito in versione finale #endif #include using namespace std; const int MAX_N = 500; // massima cardinalita' della stringa in input char s[MAX_N]; // la stringa in input int n; // lunghezza della stringa in input int opt[MAX_N +1][MAX_N +1]; /* opt[i][j] = the minimum cost of a sequence of operations that fixes the interval string s[i..j) where the character in position j is the first excluded. Here i <= j and s[i,i) is the empty string. */ int main() { ifstream fin("input.txt"); assert( fin ); fin >> n; for(int i = 0; i < n; i++) fin >> s[i]; fin.close(); for(int i = n-1; i >= 0; i--) for(int j = i; j <= n; j++) if( i >= j ) opt[i][j] = 0; else { opt[i][j] = 1 + opt[i+1][j]; // DELETION del carattere in posizione i for(int h = i+1; h < j; h++) // the character in position i is mated with the character in position h opt[i][j] = min( opt[i][j], opt[i+1][h] + opt[h+1][j] + ( (s[i] != '(') ? 1 : 0 ) + ( (s[h] != ')') ? 1 : 0 ) ); // cout << "opt[" << i << "," << j << "] = " << opt[i][j] << endl; } ofstream fout("output.txt"); fout << opt[0][n] << endl; fout.close(); return 0; }