/** * Definition for a category handler. * class CategoryHandler { * public CategoryHandler(int[] categories); * public boolean haveSameCategory(int a, int b); * }; */classSolution{privateint[]p;publicintnumberOfCategories(intn,CategoryHandlercategoryHandler){p=newint[n];for(inti=0;i<n;++i){p[i]=i;}for(inta=0;a<n;++a){for(intb=a+1;b<n;++b){if(categoryHandler.haveSameCategory(a,b)){p[find(a)]=find(b);}}}intans=0;for(inti=0;i<n;++i){if(i==p[i]){++ans;}}returnans;}privateintfind(intx){if(p[x]!=x){p[x]=find(p[x]);}returnp[x];}}
/** * Definition for a category handler. * class CategoryHandler { * public: * CategoryHandler(vector<int> categories); * bool haveSameCategory(int a, int b); * }; */classSolution{public:intnumberOfCategories(intn,CategoryHandler*categoryHandler){vector<int>p(n);iota(p.begin(),p.end(),0);function<int(int)>find=[&](intx){if(p[x]!=x){p[x]=find(p[x]);}returnp[x];};for(inta=0;a<n;++a){for(intb=a+1;b<n;++b){if(categoryHandler->haveSameCategory(a,b)){p[find(a)]=find(b);}}}intans=0;for(inti=0;i<n;++i){ans+=i==p[i];}returnans;}};