难题(1761E)

题目链接

题目大一:

保证是一个完整图,输出最小操作数。

 

AC代码:、

#include <bits/stdc++.h>
#define mod 1000000007
using namespace std;

int e[4010][4010], fa[4010];
int ff(int x)
{
	if(fa[x] == x) return x;
	return fa[x] = ff(fa[x]);
}

vector<int> s[4010];
vector<vector<int> > c;

bool check(vector<int> v)
{
	for (auto x : v)
	{
		for (auto y : v)
		{
			if (x != y && !e[x][y]) return 0;
		}
	}

	return 1;
}

int op(vector<int> v)
{
	int deg[4010] = {};
	for (auto x : v)
	{
		for (auto y : v)
		{
			deg[x] += e[x][y];
		}
	}

	pair<int, int> mn = {1e9, 1e9};
	for (auto x : v)
	{
		mn = min(mn, make_pair(deg[x], x));
	} 

	return mn.second;
}

void solved()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; i ++ )
	{
		fa[i] = i;
		s[i].clear();
	}

	c.clear();
	int ID = 0;
	for (int i = 1; i <= n; i ++ )
	{
		string ss;
		cin >> ss;
		int cnt = 0;
		for (int j = 0; j < n; j ++ )
		{
			e[i][j + 1] = ss[j] - '0';
			if (e[i][j + 1]) fa[ff(i)] = ff(j + 1), cnt ++; 
		}
		if (!cnt) ID = i;
	}

	for (int i = 1; i <= n; i ++ )
	{
		s[ff(i)].push_back(i);
	}

	for (int i = 1; i <= n; i ++ )
	{
		if (s[i].size()) c.push_back(s[i]);
	}

	if (c.size() == 1)
	{
		cout << "0\n";
		return ;
	}

	if (ID)
	{
		cout << "1\n";
		cout << ID << '\n';
		return ;
	}

	for (auto t : c)
	{
		if (!check(t))
		{
			cout << 1 << '\n' << op(t) << '\n';
			return ;
		}
	}

	if (c.size() == 2)
	{
		if (c[0].size() > c[1].size()) swap(c[0], c[1]);
		cout << c[0].size() << '\n';
		for (auto t : c[0]) cout << t << ' ';
		cout << '\n';
		return ;
	}

	cout << "2\n";
	cout << c[0][0] << ' ' << c[1][0] << '\n';

}

int main()
{
	ios :: sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	int t;
	cin >> t;
	while (t -- ) solved();

	return 0;
}

 

posted @ 2022-11-21 15:10  Luli&  阅读(25)  评论(0编辑  收藏  举报