標籤:
不知道為什麼比賽的時候一直想著用DFS 來寫
一直想剪枝結果還是TLE = =
這題資料量不大,又是問最優解,那麼一般來說是用 BFS 來寫
int commandi[4] = {1, 2, 3, 4};
我定義了一個方向數組,其實題目意思中的,指標移動還有操作版的變化本質上都是指標的移動
在此只需要 額外定義一個變數 cur 在數組 commandi 中迴圈移動即可
這道題目還是因為資料量不大吧,直接用 STL 中的 Queue 即可,優先隊列肯定會更快。
總體來說,還是一道容易題。
Source Code :
//#pragma comment(linker, "/STACK:16777216") //for c++ Compiler#include <stdio.h>#include <iostream>#include <fstream>#include <cstring>#include <cmath>#include <stack>#include <string>#include <map>#include <set>#include <queue>#include <list>#include <vector>#include <algorithm>#define Max(a,b) (((a) > (b)) ? (a) : (b))#define Min(a,b) (((a) < (b)) ? (a) : (b))#define Abs(x) (((x) > 0) ? (x) : (-(x)))#define MOD 1000000007#define pi acos(-1.0)using namespace std;typedef long long ll ;typedef unsigned long long ull ;typedef unsigned int uint ;typedef unsigned char uchar ;template<class T> inline void checkmin(T &a,T b){if(a>b) a=b;}template<class T> inline void checkmax(T &a,T b){if(a<b) a=b;}const double eps = 1e-7 ;const int N = 210 ;const int M = 1100011*2 ;const ll P = 10000000097ll ;const int MAXN = 10900000 ;const int INF = 0x3f3f3f3f ;const int dir_x[5] = {0, 0, 0, -1, 1};const int dir_y[5] = {0, -1, 1, 0, 0};struct sc { int x, y; int time; int cur;} st, ed;int n, m, p;char a[20][20];bool vis[20][20][5];int commandi[4] = {1, 2, 3, 4};queue <sc> q;bool check (int x, int y) { return x >= 1 && x <= n && y >= 1 && y <= m;}int left (int &cur) { cur = (cur - 1 + 4) % 4;}int right (int & cur) { cur = (cur + 1 + 4) % 4;}void solve (struct sc v) { ++v.time; if (v.time % p == 0) { left (v.cur); } if (vis[v.x][v.y][commandi [v.cur]] == false) { vis[v.x][v.y][commandi [v.cur]] = true; q.push (v); }}void bfs () { int ans = -INF; sc e; e = st; e.time = 0; e.cur = 0; memset (vis, 0, sizeof (vis)); vis [e.x][e.y][commandi [e.cur]] = true; q.push (e); while (!q.empty ()) { sc u = q.front (); q.pop (); if ((u.x == ed.x && u.y == ed.y) || ‘$‘ == a[u.x][u.y]) { ans = u.time; break; } sc v = u; //to left left (v.cur); solve (v); v = u; //to right right (v.cur); solve (v); v = u; //wait solve (v); v = u; //press int dr = commandi [v.cur]; v.x += dir_x[dr]; v.y += dir_y[dr]; if (!check (v.x, v.y)) continue; if (‘*‘ == a[v.x][v.y]) continue; solve (v); } if (-INF == ans) { cout << "YouBadbad" << endl; } else { cout << ans << endl; }}int main () { int i, j, t; cin >> t; while (t--) { while (!q.empty ()) q.pop (); cin >> n >> m >> p; for (i = 1; i <= n; ++i) { for (j = 1; j <= m; ++j) { cin >> a[i][j]; if (‘@‘ == a[i][j]) { st.x = i; st.y = j; } else if (‘$‘ == a[i][j]) { ed.x = i; ed.y = j; } } } bfs (); } return 0;}/*10 10 3@..................................................................................................$10 5 3@................................................$*/
ZOJ 3865 Superbot BFS 搜尋