This is an easy problem from uva judge http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2498
Union Find disjoint sets.
How I did it
- I read the number of cases.
- For each case I read the number of friendships to read.
- For each name I check if the name exist in a map. If a name is not in the map I added to the map.
- I call union_set.
- Print the size of the set with the name of one person in the new friendship.
Hints
- For each friendship you need to print one line with the size of the set. i.e (3 4 print ans, 3 4 print ans again).
- The answer is just union find.
Code
#include <iostream> #include <cstdio> #include <map> #define ELEMENTS 100002 using namespace std; map<string,int> myMap; int index; int parent[ELEMENTS]; int rank[ELEMENTS]; int numDisjointSets; void make_sets(int number_of_elements) { numDisjointSets = number_of_elements; int i; for(i = 0; i < number_of_elements; i++) { parent[i] = i; rank[i] = 1; } } int find_set(int element) { if(element != parent[element]) parent[element] = find_set(parent[element]); return parent[element]; } bool isSameSet(int i, int j) { return find_set(i) == find_set(j); } void set_union(int x, int y)//where x and y are elements of different sets { int rx, ry; //roots or representatives of x and y sets rx = find_set(x); ry = find_set(y); if(rx == ry) // it means the elements already are in the same set return; numDisjointSets--; if(rank[rx] > rank[ry]) { rank[rx] += rank[ry]; parent[ry] = rx; } else { rank[ry] += rank[rx]; parent[rx] = ry; } } int getNumSets() { return numDisjointSets; } int sizeOfSet(int i) { return rank[find_set(i)]; } void setIndex(string str) { if(myMap.find(str) == myMap.end()) myMap[str] = index++; } int main() { string name1, name2; int casos, friendship; scanf("%d", &casos); while(casos--) { index = 0; scanf("%d", &friendship); make_sets(ELEMENTS); myMap.clear(); for(int x=0; x<friendship; x++) { cin>>name1>>name2; setIndex(name1); setIndex(name2); set_union(myMap[name1], myMap[name2]); int answer = sizeOfSet(myMap[name1]); printf("%d\n", answer); } } return 0; }