90分求助,第二个点TLE
查看原帖
90分求助,第二个点TLE
46994
风蚀_极影楼主2019/12/7 11:31
#include <stdio.h>
#include <string.h>

int map[1010][1010];
bool book[1010][1010];
int pir[1010][1010];
long long int link[1000010];
long long int count;
long long int n,m;
long long int ans[1001][1001]; 
int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
struct node{
	int x;
	int y;
}que[1000010];

long long int bfs(long long int x,long long int y)
{
	long long int sum = 1;
	long long int tail = 1,head = 1;
	//memset(que,0,sizeof(struct node) * 100010);
	memset(book,false,sizeof(book));
	que[tail].x = x;
	que[tail].y = y;
	book[x][y] = true;
	pir[x][y] = ++count;
	tail ++;
	
	long int i;
	long long int nx,ny;
	while(head < tail)
	{
		for(i = 0 ; i <= 3 ; i ++)
		{
			nx = que[head].x + dir[i][0];
			ny = que[head].y + dir[i][1];
			
			if(nx < 1 || nx > n || ny < 1 || ny > n)
			{
				continue;
			}
			if(!book[nx][ny] && map[que[head].x][que[head].y] != map[nx][ny])
			{
				book[nx][ny] = true;
				pir[nx][ny] = count;
				sum ++;
				que[tail].x = nx;
				que[tail].y = ny;
				tail ++;
			}
		}
		head ++;
	}
	/*
	for(i = 1 ; i <= tail ; i ++)
	{
		ans[que[i].x][que[i].y] = sum;
	}*/
	return link[count] = sum;
}

int main()
{
	long long int t;
	long long int qx,qy;
	//freopen("testdata (1) (2).in","r",stdin);
	scanf("%lld%lld",&n,&m);
	for(long int i = 1 ; i <= n ; i ++)
	{
		for(long int j = 1 ; j <= n ; j ++)
		{
			scanf("%1d",&map[i][j]);
		}
	}
	//fclose(stdin);
	/*
	for(int i = 1 ; i <= n ; i ++)
	{
		for(int j = 1 ; j <= n ; j++)
		{
			if(!book[i][j])
			{
				bfs(i,j);
			}
		}
	}
	while(m --)
	{
		scanf("%d%d",&qx,&qy);
		printf("%lld\n",ans[qx][qy]);
	}
	*/
	for(long int i = 1 ; i <= m ; i ++)
	{
		scanf("%lld%lld",&qx,&qy);
		if(pir[qx][qy] != 0)
		{
			printf("%lld\n",link[pir[qx][qy]]);
		}
		else
		{
			printf("%lld\n",bfs(qx,qy));
		}
	}
	//fclose(stdin);
	
	return 0;
}
2019/12/7 11:31
加载中...