L2_024部落
用person收集總人數
用vis[]數組來判斷這個人是否出現過 ?
如果 vis[i] == false
那么 vis[i] = true; person++;
?
用int bl 來收集部落數
加一個人就bl++ 合并兩個人就bl--
用并查集判斷兩個人是否在同一個部落
?
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int n,k,q,t;
int father[10001];
int bl = 0;
int person = 0;
int vis[10001];
int getFather(int x);
void Union(int x, int y);
int main()
{
?? ?int last;
?? ?memset(vis,false,sizeof(vis));
?? ?cin>>n;
?? ?for(int i=0;i<n;i++){
?? ??? ?cin>>k;
?? ??? ?for(int j=0;j<k;j++){
?? ??? ??? ?cin>>t;
?? ??? ??? ?if(!vis[t]){
?? ??? ??? ??? ?vis[t] = true;
?? ??? ??? ??? ?father[t] = t;
?? ??? ??? ??? ?person++;
?? ??? ??? ??? ?bl++;
?? ??? ??? ?}
?? ??? ??? ?if(j){
?? ??? ??? ??? ?Union(last, t);
?? ??? ??? ?}
?? ??? ??? ?last = t;
?? ??? ?}
?? ?}?? ?
?? ?cout<<person<<" "<<bl<<endl;
?? ?cin>>q;
?? ?int a,b;
?? ?for(int i=0;i<q;i++){
?? ??? ?cin>>a>>b;
?? ??? ?if(getFather(a) == getFather(b))
?? ??? ??? ?cout<<"Y"<<endl;
?? ??? ?else
?? ??? ??? ?cout<<"N"<<endl;
?? ?}
?? ?return 0;
}
int getFather(int x){
?? ?if(father[x] == x)
?? ??? ?return x;
?? ?else
?? ??? ?return father[x] = getFather(getFather(father[x]));
}
void Union(int x,int y){
?? ?int fx = getFather(x);
?? ?int fy = getFather(y);
?? ?if(fx!=fy){
?? ??? ?father[fx] = fy;
?? ??? ?bl--;
?? ?}
}
總結
- 上一篇: 初入职场的自己
- 下一篇: android 使用shape自定义圆角