Created
January 30, 2013 04:45
-
-
Save krisys/4670716 to your computer and use it in GitHub Desktop.
Balanced Smileys - At any index, the number of closing brackets should be less than or equal to the number of opening brackets, if it is less, then the difference of closing brackets and opening brackets should be equal to the number of happy smileys. And a similar logic should be applied from the end considering the number of sad smileys.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <map> | |
#include <set> | |
#include <algorithm> | |
#include <iostream> | |
#include <cstdio> | |
#define FOR(i,a,b) for(int i=a;i<b;i++) | |
#define REP(i,a) FOR(i, 0, a) | |
#define all(a) a.begin(), a.end() | |
#define SORT(a) sort(all(a)) | |
#define VI vector<int> | |
using namespace std; | |
bool is_valid(string &s){ | |
int n = s.length(); | |
VI opening(n), closing(n), happy(n), sad(n); | |
FOR(i, 0, n){ | |
if(i){ | |
opening[i] = opening[i-1]; closing[i] = closing[i-1]; | |
happy[i] = happy[i-1]; sad[i] = sad[i-1]; | |
} | |
if(s[i]== '('){ | |
opening[i]++; | |
if(i - 1 >= 0 && s[i-1] == ':') | |
sad[i]++; | |
} | |
else if(s[i] == ')'){ | |
closing[i]++; | |
if(i - 1 >= 0 && s[i-1] == ':') | |
happy[i]++; | |
} | |
} | |
FOR(i, 0, n){ | |
if(opening[i] < closing[i]) { | |
if(happy[i] < (closing[i] - opening[i])) | |
return false; | |
} | |
} | |
opening = VI(n); | |
closing = VI(n); | |
happy = VI(n); | |
sad = VI(n); | |
for(int i = n-1; i>0; i--){ | |
if(i != n-1){ | |
opening[i] = opening[i+1]; closing[i] = closing[i+1]; | |
happy[i] = happy[i+1]; sad[i] = sad[i+1]; | |
} | |
if(s[i]== '('){ | |
opening[i]++; | |
if(i - 1 >= 0 && s[i-1] == ':') | |
sad[i]++; | |
} | |
else if(s[i] == ')'){ | |
closing[i]++; | |
if(i - 1 >= 0 && s[i-1] == ':') | |
happy[i]++; | |
} | |
} | |
for(int i = n-1; i>=0; i--){ | |
if(opening[i] > closing[i]) { | |
if(sad[i] < (opening[i] - closing[i])) | |
return false; | |
} | |
} | |
return true; | |
} | |
int main(){ | |
int T; | |
cin >> T; | |
cin.ignore(); | |
REP(tc, T){ | |
string s; | |
getline(cin, s); | |
if(is_valid(s)) | |
cout << "Case #" << tc + 1 << ": YES" << endl; | |
else | |
cout << "Case #" << tc + 1 << ": NO" << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please check your solution with an easy test case: "(", your solution returns YES, which is definitely wrong