今天ABC的C咋优化
  • 板块灌水区
  • 楼主shy_lihui
  • 当前回复7
  • 已保存回复7
  • 发布时间2024/12/7 21:44
  • 上次更新2024/12/8 09:26:44
查看原帖
今天ABC的C咋优化
1053122
shy_lihui楼主2024/12/7 21:44

我是【数据删除】,两个搜索都没过,

bfs:

#include<bits/stdc++.h>

using namespace std;
int n,m,d;
char a[1005][1005];
bool vis[1005][1005];
vector<pair<int,int>>e;
int ans;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
struct Node
{
	int x;
	int y;
	int step;
};

void bfs(int x,int y)
{
	queue<Node>q;
	q.push({x,y,d});
	vis[x][y]=1;

	while(!q.empty())
	{
		Node noww=q.front();
		q.pop();
		if(noww.step==0)
		{
			continue;
		}
		for(int i=0;i<4;i++)
		{
			int xx=noww.x+dx[i];
			int yy=noww.y+dy[i];
			if(xx>=1 && xx<=n && yy>=1 && yy<=m && a[xx][yy]!='#')
			{
				if(vis[xx][yy]==0)
				{
					ans++;
				}
				vis[xx][yy]=1;
				q.push({xx,yy,noww.step-1});
			}
		}
	}
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin>>n>>m>>d;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cin>>a[i][j];
			if(a[i][j]=='H')
			{
				e.push_back(make_pair(i,j));
			}
		}
	}
	ans+=e.size();
	for(auto i:e)
	{
		vis[i.first][i.second]=1;
	}
	for(auto i:e)
	{
		bfs(i.first,i.second);
	}
	
	cout<<ans;
	return 0;
}

dfs:

#include<bits/stdc++.h>
using namespace std;
int n,m,d;
char a[1005][1005];
bool vis[1005][1005];
vector<pair<int,int>> e;
int ans;
void dfs(int x,int y,int t)
{
	if(t==-1||x<1||x>n||y<1||y>m||a[x][y]=='#')
	{
		return;
	}
	vis[x][y]=1;
	dfs(x-1,y,t-1);
	dfs(x,y-1,t-1);
	dfs(x+1,y,t-1);
	dfs(x,y+1,t-1);
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin>>n>>m>>d;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cin>>a[i][j];
			if(a[i][j]=='H')
			{
				e.push_back(make_pair(i,j));
			}
		}
	}
	for(auto i:e)
	{
		dfs(i.first,i.second,d);
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			ans+=vis[i][j];
		}
	}
	cout<<ans;
	return 0;
}
2024/12/7 21:44
加载中...