Created
August 17, 2013 10:38
-
-
Save loosechainsaw/6256313 to your computer and use it in GitHub Desktop.
Quick Find Algorithm and DataStructure
This file contains hidden or 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> | |
template<int N> | |
class quick_find{ | |
public: | |
quick_find() | |
{ | |
for(int i =0; i < N; ++i){ | |
elements[i] = i; | |
} | |
} | |
bool connected(int p, int q) const{ | |
return (elements[p] == elements[q]); // are they in the same connected component? | |
} | |
void union_components(int p, int q){ | |
auto pvalue = elements[p]; | |
auto qvalue = elements[q]; | |
for(int i =0; i < N; ++i) | |
{ | |
if(elements[i] == qvalue) | |
elements[i] = pvalue; | |
} | |
} | |
private: | |
int elements[N]; | |
}; | |
int main(){ | |
quick_find<10> q; | |
q.union_components(0,1); | |
q.union_components(1,2); | |
using namespace std; | |
cout << "Connected: " << boolalpha << (q.connected(0,1)) << endl; | |
cout << "Connected: " << boolalpha << (q.connected(1,2)) << endl; | |
cout << "Connected: " << boolalpha << (q.connected(2,2)) << endl; | |
cout << "Connected: " << boolalpha << (q.connected(0,8)) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment