求更优解
查看原帖
求更优解
1334925
徐振轩2011楼主2024/9/15 13:45

题目

我的代码:

#include <bits/stdc++.h>
using namespace std;
int n,x,f[305][10],ans[305][10];
int dx[8] = {1,1,1,0,0,-1,-1,-1};
int dy[8] = {-1,0,1,-1,1,-1,0,1};
struct node{
	int x,y,step;
};
queue <node> q;
void paint (int c,int s){
	if (s == 0){
		for (int i = 0 ; i < 5 ; i++){
			for (int j = 1 ; j <= 5 ; j++){
				if (i == 0 || i == 4 || j == 1 || j == 5){
					f[c * 5 - i][j] = 1;
				}
			}
		}
	}else if (s == 1){
		for (int i = 0 ; i < 5 ; i++){
			f[c * 5 - i][5] = 1;
		}
		for (int i = 1 ; i <= 5 ; i++){
			f[c * 5 - 2][i] = 1;
		}
		f[c * 5 - 3][2] = 1;
		f[c * 5 - 4][3] = 1;
	}else if (s == 2){
		for (int i = 0 ; i < 5 ; i++){
			for (int j = 1 ; j <= 5 ; j++){
				if (!(j == 2 && i != 0 || j == 4 && i != 4)){
					f[c * 5 - i][j] = 1;
				}
			}
		}
	}else if (s == 3){
		for (int i = 0 ; i < 5 ; i++){
			for (int j = 1 ; j <= 5 ; j++){
				if (!((j == 2 || j == 4) &&  i != 0)){
					f[c * 5 - i][j] = 1;
				}
			}
		}
	}else if (s == 4){
		for (int i = 1 ; i <= 5 ; i++){
			f[c * 5][i] = 1;
		}
		for (int i = 1 ; i <= 3 ; i++){
			f[c * 5 - 4][i] = 1;
		}
		for (int i = 1 ; i <= 3 ; i++){
			f[c * 5 - i][3] = 1;
		}
	}else if (s == 5){
		for (int i = 0 ; i < 5 ; i++){
			for (int j = 1 ; j <= 5 ; j++){
				if (!(j == 4 && i != 0 || j == 2 && i != 4)){
					f[c * 5 - i][j] = 1;
				}
			}
		}
	}else if (s == 6){
		for (int i = 0 ; i < 5 ; i++){
			for (int j = 1 ; j <= 5 ; j += 2){
				f[c * 5 - i][j] = 1;
			}
		}
		f[c * 5][2] = 1;
		f[c * 5 - 4][4] = 1;
		f[c * 5][4] = 1;
	}else if (s == 7){
		for (int i = 0 ; i < 5 ; i++){
			f[c * 5 - i][1] = 1;
		}
		for (int i = 1 ; i <= 5 ; i++){
			f[c * 5][i] = 1;
		}
	}else if (s == 8){
	    for (int i = 0 ; i < 5 ; i++){
			for (int j = 1 ; j <= 5 ; j += 2){
				f[c * 5 - i][j] = 1;
			}
		}
		for (int i = 1 ; i <= 5 ; i++){
			f[c * 5 - 4][i] = 1;
		}
		for (int i = 1 ; i <= 5 ; i++){
			f[c * 5][i] = 1;
		}
	}else if (s == 9){
		for (int i = 0 ; i < 5 ; i++){
			for (int j = 1 ; j <= 5 ; j += 2){
				f[c * 5 - i][j] = 1;
			}
		}
		f[c * 5 - 4][2] = 1;
		f[c * 5][2] = 1;
		f[c * 5][4] = 1;
	}
}
void bfs (){
	q.push((node){1,1,0});
	ans[1][1] = 0;
	while (!q.empty()){
		node tmp = q.front();
		q.pop();
		for (int i = 0 ; i < 8 ; i++){
			int nx = tmp.x + dx[i];
			int ny = tmp.y + dy[i];
			if (nx < 1 || nx > (n * 5) || ny < 1 || ny > 5 || f[nx][ny] == 0 || ans[nx][ny] <= 1000){
				continue;
			}
			q.push((node){nx,ny,tmp.step + 1});
			ans[nx][ny] = tmp.step + 1;
		}
	}
}
int main(){
	cin >> n;
	for (int i = 1 ; i <= n ; i++){
		cin >> x;
		paint(i,x);
	}
	memset (ans,127,sizeof(ans));
	bfs ();
	if (ans[n * 5][5] <= 1e6) cout << ans[n * 5][5];
	else cout << -1;
	return 0;
}
2024/9/15 13:45
加载中...