Advertisement
Guest User

Poltu and Graph

a guest
Dec 10th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. typedef unsigned long long ull;
  5. #define INF 9223372036854775806
  6. #define pb push_back
  7. #define mp make_pair
  8. #define MOD 1000000007
  9. #define PI 2*acos(0.0)
  10. ll mod(ll B,ll M){ll X=B%M; if(X>=0) return X; else return M+X;}
  11. ///cin.ignore();
  12. ll max(ll a,ll b) {if(a>b) return a; else return b;} ll min(ll a,ll b) {if(a<b) return a; else return b;}
  13. ll fx4[]={1,-1,0,0}; ll fy4[]={0,0,1,-1};
  14. struct ff{
  15.     ll u,v,w;
  16.     ff(ll a,ll b,ll c){
  17.         u=a; v=b; w=c;
  18.     }
  19. };
  20. bool comp(ff a,ff b){
  21.     return a.w<b.w;
  22. }
  23. ll par[300000],ssize[300000];
  24. ll Find(ll r){
  25.     if(par[r]==r) return r;
  26.     else return par[r]=Find(par[r]);
  27. }
  28. void Union(ll x,ll y){
  29.     ll px=Find(x);
  30.     ll py=Find(y);
  31.     if(px!=py){
  32.         par[py]=px;
  33.         ssize[px]+=ssize[py];
  34.     }
  35. }
  36. int main()
  37. {
  38.     //freopen("C:/Users/Md Faizul Haque/Desktop/Solving/input.txt","r",stdin);
  39.     //freopen("C:/Users/Md Faizul Haque/Desktop/Solving/output.txt","w",stdout);
  40.  
  41.     ll t,n,m,x,y,w,k,q,r,p,cs;
  42.     cin>>n>>m;
  43.     for(int i=1;i<=n;i++){
  44.         par[i]=i;
  45.         ssize[i]=1;
  46.     }
  47.     vector<ff> g;
  48.     for(int i=1;i<=m;i++){
  49.         cin>>x>>y>>w;
  50.         g.pb(ff(x,y,w));
  51.     }
  52.     sort(g.begin(),g.end(),comp);
  53.     cin>>q;
  54.     vector<ff> query;
  55.     for(int i=1;i<=q;i++){
  56.         cin>>x>>y;
  57.         query.pb(ff(x,i,y));
  58.     }
  59.     sort(query.begin(),query.end(),comp);
  60.     ll ans[q+4]={0};
  61.     for(int i=1;i<=q;i++) ans[i]=1;
  62.     int i=0,j=0;
  63.     while(i<q || j<m){
  64.         if(i>=q) break;
  65.         ll s=query[i].u; ll lim=query[i].w; ll idx=query[i].v;
  66.         if(j>=m){
  67.             ll ps=Find(s);
  68.             ans[idx]=ssize[ps];
  69.             i++;
  70.             continue;
  71.         }
  72.         x=g[j].u; y=g[j].v; w=g[j].w;
  73.         if(w<=lim){
  74.             Union(x,y);
  75.             j++;
  76.             ll ps=Find(s);
  77.             ans[idx]=ssize[ps];
  78.         }
  79.         else{
  80.             ll ps=Find(s);
  81.             ans[idx]=ssize[ps];
  82.             i++;
  83.         }
  84.     }
  85.  
  86.     for(int i=1;i<=q;i++) cout<<ans[i]<<endl;
  87.  
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement