TLE 50求助悬关
查看原帖
TLE 50求助悬关
973971
xfx2011楼主2024/5/1 15:21
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2000 + 10;
struct n{
	int x, y; 
	bool operator < (const n &z) const 
	{
		if (x != z.x) 
			return x < z.x;
		return 
			y < z.y;
	}
}a[maxn];
int n;
struct queue_node{
	int x,y,step;
}q[maxn * maxn];
int res[maxn][maxn];
int vis[maxn][maxn];
struct nodek{
	int u,v,w;
    bool operator < (const nodek &ll) const
	{
        return w < ll.w;
    }
}e[maxn * maxn];
int m;
int fa[maxn];
int l = 0;
int d[8][2] = {{-1,2},{1,2},{2,1},{-2,1},{-1,-2},{1,-2},{2,-1},{-2,-1}};
void bfs(int sx,int sy){
	memset(vis,0,sizeof(vis));
	int head = 1,tail = 1;
	q[tail] = {sx,sy,1};
	tail ++;
	vis[sx][sy] = 1;
	while(head < tail){
		int x0 = q[head].x;
		int y0 = q[head].y;
		int step = q[head].step;
		for(int i = 0;i < 8;i ++){
			int nx = x0 + d[i][0];
			int ny = y0 + d[i][1];
			if(nx >= 1 && nx <= m && ny >= 1 && ny <= m && !vis[nx][ny]){
				if(res[nx][ny]){
					l ++;
					e[l] = {res[sx][sy],res[nx][ny],step};
				}
				vis[nx][ny] = 1;
				q[tail] = {nx,ny,step + 1};
				tail ++;
 			}
		}
		head ++;
	}
}
bool cmp(nodek a,nodek b){
	return a.w < b.w;
}
int find(int i){
	return i == fa[i] ? i : fa[i] = find(fa[i]);
}
int ans;
void k(){
	int tot;
	ans = tot = 0;
	for(int i = 1;i <= l;i ++){
		int x = e[i].u;
		int y = e[i].v;
		if(find(x) == find(y))
			continue;
		fa[find(x)] = find(y);
		ans += e[i].w;
		tot ++;
		if(tot == n - 1)
			return ;
	}
}
int main(){
	freopen("example.in","r",stdin);
	freopen("example.out","w",stdout);
	cin >> n >> m;
	for(int i = 1;i <= n;i ++)
		cin >> a[i].x >> a[i].y;
	sort(a + 1,a + 1 + n);
	for(int i = 1;i <= n;i ++)
		res[a[i].x][a[i].y] = i;	
	for(int i = 1;i <= n;i ++)
		bfs(a[i].x,a[i].y);
	for(int i = 1;i <= n;i ++)
		fa[i] = i;
	sort(e + 1,e + 1 + l);
	k();
	cout << ans + n - 1;
 	return 0;
}
2024/5/1 15:21
加载中...