/* Subject: Contest submission for problem #1, file 1.cc */ /* cs188-ah@imail.EECS.Berkeley.EDU */ /* Wed Sep 17 19:30:59 PDT 2003 */ /*___CONTEST_SUBMISSION___ cs188-ah 1 */ //Estimated time: 2 hours //Time 3 30 minutes //Problems: 1. Getting input parsed correctly took 1 hour 30 minutes // 2. Thinking about the problem incorrectly, trying to over do it with graph theory // and worrying about loops in the if statements when it wasn't necessary to really handle // loops. Wasted about 1 hour pondering this, until I realized a solution // #include #include #include using namespace std; struct statement { statement() : snum(-1), next1(-1), next2(-1), defined(0), lhs("undefined"), rhs(0) {} int next1, next2, snum; vector defined; string lhs; vector rhs; bool terminate; }; vector statements; int getif(statement& s); void getf(statement& s); void getassign(statement& s); statement* getstatement(int snum) { char c; string f; int next2; statement* ns = new statement(); ns->snum = snum; cin >> f; if (f == "if") { getf(*ns); cin >> f; // goto cin >> next2; //m cin >> f; // semicolin ns->next2 = next2; } else if (f.find("stop") != string::npos) { ns->terminate = true; if (f == "stop;") while(! isspace(cin.peek())) cin.get(c); else { while(isspace(cin.peek())) cin.get(c); cin.get(c); } return ns; } else { ns->lhs = f; cin >> f; //equal getf(*ns); cin >> f; //semicolon } ns->next1 = snum + 1; return ns; } void getf(statement& s) { char c = '0'; do { cin.get(c); } while(isspace(c)); cin.get(c); // F( do { if (isalpha(c)) s.rhs.push_back(c); cin.get(c); } while(c != ')'); } //are all the variables in a also in b? bool inset(vector& a, vector& b) { if ((a.size() == 0) && (b.size() == 0)) return true; if (b.size() < a.size()) return false; for(int ii = 0; ii < a.size(); ii++) { bool a_in_b = false; for(int jj = 0; jj < b.size(); jj++) if (a[ii] == b[jj]) a_in_b = true; if (!a_in_b) {return false;} } return true; } bool checksequence(int in, int out, vector defined) { for(int ii = in; ii < out; ii++) { statement* s = statements[ii]; // x = F()? if ((s->rhs.size() == 0) && s->lhs != "undefined") { defined.push_back(s->lhs[0]); continue; } // x = F(y) y undefined if (!inset(s->rhs, defined)) return false; // x = F(y) y defined if (s->next2 == -1) { defined.push_back(s->lhs[0]); continue; } // if .... if ((s->next2 > s->snum) && (!checksequence(s->next2, out, defined))) return false; } return true; } int main(int argc, char* argv[]) { int setnum = 0; int snum = -1; char c = '0'; while (!cin.eof()) { if(!(cin >> snum)) break; do { cin.get(c); } while(c != ':'); statement* ns = getstatement(snum); statements.push_back(ns); if(ns->terminate) { vector defines; if (checksequence(0, statements.size(), defines)) cout << "Set " << setnum << ": No use before definition" << endl; else cout << "Set " << setnum << ": Possible use before definition" << endl; setnum++; statements.clear(); } } }