spj TLE了?
我找了考试的数据来测试,程序是没问题的
https://www.luogu.com.cn/record/196629753
我的代码:
#include <cstdio>
#include <cassert>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <vector>
#include <array>
#include <iostream>
#include <numeric>
#include <random>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <queue>
#define rep(i, n) for (int i = 1, i##num=(n); i <= i##num; i++)
#define rep0(i, n) for (int i = 0, i##num=(n); i < i##num; i++)
#define rep2(i, x, y) for(int i=(x), i##num=(y); i <= i##num; i++)
#define repr(i, x, y) for(int i=(x), i##num=(y); i >= i##num; i--)
using namespace std;
using LL = long long;
const int maxn = 6;
const LL inf = 1000000000000LL;
int n, m;
char a[maxn][maxn];
bool b[maxn][maxn], result[maxn][maxn];
int ans, startx, starty;
bool vis[maxn][maxn];
constexpr int dx[4]={1,-1,0,0};
constexpr int dy[4]={0,0,1,-1};
int cnt_connected;
void dfs2_check(int x, int y){
cnt_connected++;
vis[x][y] = true;
rep0(dir, 4){
int x2 = x + dx[dir];
int y2 = y + dy[dir];
if (0<=x2&&x2<n&&0<=y2&&y2<m)
if(b[x2][y2] && !vis[x2][y2])
dfs2_check(x2, y2);
}
}
bool is_connected(int expected_num){
memset(vis, false, sizeof(vis));
cnt_connected = 0;
dfs2_check(startx, starty);
return cnt_connected == expected_num;
}
int cnt_later[maxn][maxn];
void dfs(int x, int y, int cur, int cur_edge){
if (cur > 0 && cur_edge >= cur) return;
if (cur + cnt_later[x][y] <= ans) return;
if (x==n){
if (cur <= ans) return;
if (cur_edge != cur - 1) return;
if (is_connected(cur)){
ans = cur;
rep0(i, n) rep0(j, m) result[i][j] = b[i][j];
}
return;
}
int x2 = x+(y+1)/m, y2 = (y+1)%m;
do{
if (a[x][y] == '#') break;
if (x>0&&y>0&&b[x-1][y]&&b[x][y-1]&&b[x-1][y-1]) break;
b[x][y] = true;
int edge_diff = (x>0&&b[x-1][y]?1:0) + (y>0&&b[x][y-1]?1:0);
dfs(x2, y2, cur+1, cur_edge + edge_diff);
b[x][y] = false;
}while(false);
if (a[x][y] != '+')
dfs(x2, y2, cur, cur_edge);
}
int main(){
#ifdef FISH_LOCAL
freopen("tmp.in", "r", stdin);
#endif
scanf("%d%d", &n, &m);
rep0(i, n) scanf("%s", a[i]);
rep0(i, n)
rep0(j, m)
if(a[i][j] == '+'){
startx=i;
starty=j;
break;
}
int tmp = 0;
repr(i,n-1,0)
repr(j,m-1,0){
if (a[i][j] != '.')
tmp++;
cnt_later[i][j] = tmp;
}
ans = 0;
dfs(0, 0, 0, 0);
rep0(i, n){
rep0(j, m)
if(result[i][j])
printf("+");
else if (a[i][j] == '#')
printf("#");
else
printf(".");
printf("\n");
}
return 0;
}