跳到正文

个人记录

114514

LzwzL约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月13日
篇幅
约 4 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int INF=1e14+7;
int T,n,m,book[5005][5005],num=0,vis[2500005],d[2500005],f[5005][5005];
int nt[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
char mapn[5005][5005],ans[5005][5005];
struct edge
{
    int to,wi;
};
struct dot
{
	int x,dis;
	bool operator<(const dot&LZW) const{
		return dis>LZW.dis;
	}
};
vector<edge> ve[100005];
int read()
{
    int inp=0,sign=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-') sign=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        inp=inp*10+ch-'0';
        ch=getchar();
    }
    return inp*sign;
}
void dfs(int x,int y,int col)
{
    book[x][y]=col;
    for(int i=0;i<4;i++)
    {
        int tx=x+nt[i][0];
        int ty=y+nt[i][1];
        if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&mapn[tx][ty]=='#') dfs(tx,ty,col);
    }
}
priority_queue<dot> p;
void dijkstra(int s)
{
	for(int i=1;i<=num;i++) d[i]=INF;
	d[s]=0;
	p.push(dot{s,0});
	while(!p.empty())
	{
		int k=p.top().x;
		p.pop();
		if(vis[k]) continue;
		vis[k]=1;
		for(int j=0;j<ve[k].size();j++)
		{
			int u=ve[k][j].to;
			if(d[k]+ve[k][j].wi<d[u])
			{
				d[u]=d[k]+ve[k][j].wi;
				p.push(dot{u,d[u]});
			}
		}
	}
}
signed main()
{
    freopen("fate.in","r",stdin);
    freopen("fate.out","w",stdout);
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) cin>>mapn[i][j];
    for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) if(!book[i][j]&&mapn[i][j]=='#') dfs(i,j,++num);
    for(int i=n;i>=1;i--)
    {
		for(int j=1;j<=m;j++)
		{
			f[i][j]=f[i+1][j];
			if(book[i+1][j]!=0) f[i][j]=i+1;
		}
	}
	for(int i=n;i>=1;i--)
    {
		for(int j=1;j<=m;j++)
		{
			if(book[i][j]!=0) if(book[i][j]!=book[f[i][j]][j]) ve[book[f[i][j]][j]].push_back(edge{book[i][j],f[i][j]-i-1});
		}
	}
	dijkstra(0);
	for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) ans[i][j]='.';
	for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(book[i][j]) ans[i+d[book[i][j]]][j]='#';
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++) cout<<ans[i][j];
        cout<<endl;
    }
	return 0;
}
原文