c++部落问题

 

c++部落问题_第1张图片 

class UnionFindSet
{
private:
	vectorparent_;
	vectorroot_;
	int nums;
	
public:
	UnionFindSet(int n) { nums = n; _init_(); };
	void _init_()
	{
		parent_ = vector(nums + 1, 1);
		root_ = vector(nums + 1, -1);
	}
	int Find(int e)
	{
		int j = e, i;
		while (root_[j] != -1) j = parent_[j];
		while (e != j)
		{
			i = parent_[e];
			parent_[e] = j;
			e = j;
		}
		return j;
	}
	void Union(int e, int t)
	{
		int p, q;
		p = Find(e);
		q = Find(t);
		if (p == q)
			return;
		if (parent_[p] >= parent_[q])
		{
			parent_[p] += parent_[q];
			parent_[q] = p;
			root_[p] = 1;
		}
		else
		{
			parent_[q] += parent_[p];
			parent_[p] = q;
			root_[p] = 1;
		}
	}
	int sum1()
	{
		int cnt = 0;
		for (int i = 1; i < parent_.size(); i++)
			if (root_[i] == -1)
				cnt++;
	}

};
int main()
{

	int n,d,k;
	vector>data;
	vectorp;
	cin >> n;
	while (n--)
	{
		cin >> k;
		for (int i = 0; i < k; i++)
		{
			cin >> d;
			p.push_back(d);
		}
		data.push_back(p);
		p.clear();
	};
	sets;
	for (int i = 0; i < data.size(); i++)
	{
		for (int j = 0; j < data[i].size(); j++)
			s.insert(data[i][j]);
	}
	int nums = s.size();
	UnionFindSet u(nums);
	int c1, c2, count = 0;

	for (int i = 0; i < data.size(); i++)
	{
		if (data[i].size() == 1)
			continue;
		for (int j = 1; j < data[i].size(); j++)
			u.Union(data[i][j - 1], data[i][j]);
	}
	cout << u.sum1();

	cin >> n;
	while (n--)
	{
		int a, b;
		cin >> a >> b;
		if (u.Find(a) == u.Find(b))
			cout << 'Y' << endl;
		else
			cout << 'N' << endl;
	}

	system("pause");
	return 0;
}

 

你可能感兴趣的:(c++)