Advertisement
urmisaha

Travelling is Fun - Union Find

Nov 16th, 2019
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define maxm 200001
  3. #define ll long long
  4.  
  5. using namespace std;
  6.  
  7. ll n, g, q;
  8. vector<ll> origin(maxm), dest(maxm), root(maxm), child(maxm);
  9.  
  10. ll findroot(ll x){
  11.     while(x != root[x])
  12.         x = root[x];
  13.     return x;
  14. }
  15.  
  16. void _union(ll x, ll y){
  17.     ll rootx = findroot(x);
  18.     ll rooty = findroot(y);
  19.     if(rootx == rooty)
  20.         return;
  21.     if(child[rootx] < child[rooty]){
  22.         root[rootx] = root[rooty];
  23.         child[rooty] += child[rootx];
  24.     }
  25.     else{
  26.         root[rooty] = root[rootx];
  27.         child[rootx] += child[rooty];
  28.     }
  29. }
  30.  
  31. void solve(){
  32.     if(!g){
  33.         for(ll i=0; i<q; ++i)
  34.             cout<<1<<endl;
  35.         return;
  36.     }
  37.     for(ll i=1; i<=n; ++i){
  38.         root[i] = i;
  39.         child[i] = 1;
  40.     }
  41.     for(ll i=g+1; i<=n; ++i){
  42.         if(root[i] != i)
  43.             continue;
  44.         for(ll j=2*i; j<=n; j+=i)
  45.             _union(i, j);
  46.     }
  47.     for(ll i=0; i<q; ++i)
  48.         cout<<(findroot(origin[i]) == findroot(dest[i]))<<endl;
  49. }
  50.  
  51. int main() {
  52.     ios_base::sync_with_stdio(false);
  53.     cin>>n>>g>>q;
  54.     for(ll i=0; i<q; ++i)
  55.         cin>>origin[i];
  56.     cin>>q;
  57.     for(ll i=0; i<q; ++i)
  58.         cin>>dest[i];
  59.     solve();
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement