Created
January 7, 2017 01:53
-
-
Save dudelson/91163964b17919626df926bdbd04ed4e to your computer and use it in GitHub Desktop.
My solution for UVA 11503
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 <iostream> | |
#include <map> | |
#include <string> | |
using namespace std; | |
map<string, string> p; | |
map<string, int> r, sizes; | |
inline string getSet(const string &s) { | |
if(p.find(s) == p.end()) { | |
p[s] = s; | |
r[s] = 0; | |
sizes[s] = 1; | |
return s; | |
} | |
return p[s] == s ? s : (p[s] = getSet(p[s])); | |
} | |
inline bool sameSet(string s, string t) { | |
return getSet(s) == getSet(t); | |
} | |
inline void joinSet(string s, string t) { | |
if(sameSet(s, t)) return; | |
string a = getSet(s), b = getSet(t); | |
if(r[a] < r[b]) { | |
p[a] = b; | |
sizes[b] += sizes[a]; | |
} else { | |
p[b] = a; | |
sizes[a] += sizes[b]; | |
if(r[a] == r[b]) r[a]++; | |
} | |
} | |
int n, f; | |
string s, t; | |
int main() { | |
cin >> n; | |
while(n--) { | |
p.clear(); r.clear(); sizes.clear(); | |
cin >> f; | |
while(f--) { | |
cin >> s >> t; | |
joinSet(s, t); | |
cout << sizes[getSet(s)] << '\n'; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment