Andrew Stankevich Contest 4——Driving Straight

題目連接

  • 題意:
    輸入m、n,之後是2*m-1行,2*n-1列。‘ ’表示不能通過,‘+’可以通過,‘-’、‘|’只允許一個方向通過(和符號相同的方向),求從左下角到右上角的最短路並輸出:輸出時候,儘量保持之前的運動方向。每到一個‘+’點,輸出當前採取的運動操作:R,右轉;L,左轉;F,直行。最開始的時候輸出:N,向北走;E向東走
  • 分析:
    簡單的最短路,就是輸出路徑的時候麻煩一點。右上角開始bfs求最短路,左下角開始找路徑即可
const int INF = 0x3f3f3f3f;
const double EPS = 1e-9;
const int MOD = 1000000007;
const double PI = acos(-1.0);
const int MAXN = 900;

char ipt[MAXN][MAXN];
int dp[MAXN][MAXN];
int n, m;

int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
char judge[] = {'|', '-', '|', '-'};
struct Node
{
    int x, y;
    Node(int x = 0, int y = 0) : x(x), y(y) {}
} t;
bool check(int r, int c, int dir)
{
    return ipt[r][c] == '+' || ipt[r][c] == judge[dir];
}
void bfs(int sx, int sy)
{
    queue<Node> q;
    q.push(Node(sx, sy));
    dp[sx][sy] = 0;
    while (!q.empty())
    {
        t = q.front(); q.pop();
        REP(i, 4)
        {
            if (check(t.x, t.y, i))
            {
                int tx = t.x + dx[i];
                int ty = t.y + dy[i];
                if (dp[tx][ty] == INF && ipt[tx][ty] != ' ' && ipt[tx][ty] != 0 && check(tx, ty, i))
                {
                    dp[tx][ty] = dp[t.x][t.y] + 1;
                    q.push(Node(tx, ty));
                }
            }
        }
    }
}

void display(int x, int y, int dir)
{
    if (x == 1 && y == m)
    {
        return;
    }
    int ldir = (dir + 3) % 4, rdir = (dir + 1) % 4;
    int tx, ty;
    tx = x + dx[dir]; ty = y + dy[dir];
    if (ipt[tx][ty] != 0 && dp[tx][ty] == dp[x][y] - 1)
    {
        if (ipt[x][y] == '+')
            putchar('F');
        display(tx, ty, dir);
        return;
    }

    tx = x + dx[ldir]; ty = y + dy[ldir];
    if (ipt[tx][ty] != 0 && dp[tx][ty] == dp[x][y] - 1)
    {
        if (ipt[x][y] == '+')
            putchar('L');
        display(tx, ty, ldir);
        return;
    }

    tx = x + dx[rdir]; ty = y + dy[rdir];
    if (ipt[tx][ty] != 0 && dp[tx][ty] == dp[x][y] - 1)
    {
        if (ipt[x][y] == '+')
            putchar('R');
        display(tx, ty, rdir);
        return;
    }
}

int main()
{
    freopen("straight.in", "r", stdin);
    freopen("straight.out", "w", stdout);
    while (~RII(n, m))
    {
        n = n * 2 - 1; m = m * 2 - 1;
        getchar();
        CLR(dp, INF);
        CLR(ipt, 0);
        FE(i, 1, n)
            gets(ipt[i] + 1);
        bfs(1, m);
        REP(i, 2)
        {
            int tx = n + dx[i];
            int ty = 1 + dy[i];
            if (ipt[tx][ty] != 0 && check(n, 1, i) && check(tx, ty, i) && dp[tx][ty] == dp[n][1] - 1)
            {
                puts(i ? "E" : "N");
                display(tx, ty, i);
                break;
            }
        }
        puts("");
    }
    return 0;
}

給點測試數據:
2 2
+--
|||
+++

2 2
+--
|
+

2 2
+--
+-+
--+

2 2
+++
+++
+++

2 2
+++
-++
+++

4 4
+-+ +-+
| |   |
+ +-+-+
|   -
+-+-+-+
|     |
+-+-+-+



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章