MLE求助
查看原帖
MLE求助
1023793
yaodiguoan楼主2024/7/18 18:30
#include <bits/stdc++.h>
using namespace std;
//#pragma GCC optimize(2)
//#pragma GCC optimize(3, "Ofast", "inline")
#define hh putchar('\n')
#define kg putchar(' ')
#define debug puts("debug")
//#define int long long
//#define int __int128
namespace quickread{
	template<typename T> void read(T &x){
		x=0;char c=getchar();T neg=0;
		while(!isdigit(c)) neg|=!(c^'-'),c=getchar();
		while(isdigit(c)) x=(x<<3)+(x<<1)+(c^48),c=getchar();
		if(neg) x=(~x)+1;
	}
	template<typename T> void write(T x){
		if(x<0) putchar('-'),x=~x+1;
		if(x>9) write(x/10);
		putchar(x%10^48);
	}
	inline string readstr(){
    	char ch=getchar();string str="";
		while(!isalnum(ch)) ch=getchar();
		while(isalnum(ch)){str+=ch;ch=getchar();}
		return str;
	}
	inline char readchar(){
		char ch=getchar();
		while(!isalnum(ch)) ch=getchar();
		return ch;
	}
}
using namespace quickread;
const int N=2e3+10,inf=2147483647;
struct node{int x,y;node(){x=y=0;}};
node g[N][N];
struct csp{int x,y,w;};
int n,m;
bool vis[N][N],a[N][N];
int dx[5]={0,-1,0,1,0},dy[5]={0,0,-1,0,1};
queue<csp>q;
int bfs(int x,int y,int w){
	while(!q.empty()) q.pop();
	q.push(csp{x,y,w});
	while(!q.empty()){
		x=q.front().x,y=q.front().y,w=q.front().w;
		q.pop();
		if(vis[x][y]) continue;
		vis[x][y]=1;
		if(x==n&&y==m) return w;
		for(int i=1;i<=4;i++){
			int tx=x+dx[i],ty=y+dy[i];
			if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&a[x][y]!=a[tx][ty]){
				q.push(csp{tx,ty,w+1});
				g[tx][ty].x=x,g[tx][ty].y=y;
			}
		}
	}
	return -1;
}
char solve(int x,int y){
	char ch;
	if(x==1&&y==0) ch='U';
	else if(x==-1&&y==0) ch='D';
	else if(x==0&&y==1) ch='L';
	else ch='R';
	return ch;
}
void print(int x,int y){
	if(x==1&&y==1) return;
	print(g[x][y].x,g[x][y].y);
	putchar(solve(g[x][y].x-x,g[x][y].y-y));
}
void work(){
	memset(vis,0,sizeof(vis));
	memset(a,0,sizeof(a));
	read(n),read(m);
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j)
			a[i][j]=readchar()=='1';
	int k=bfs(1,1,0);
	if(k==-1) puts("-1");
	else{
		write(k),hh;
		print(n,m),hh;
	}
}
signed main(){
//	ios::sync_with_stdio(0);
//	cin.tie(0);cout.tie(0);
	int t;read(t);
	while(t--) work();
	return 0;
}

2024/7/18 18:30
加载中...