跳到正文

题解

题解:AT_arc177_c [ARC177C] Routing

Ter3nce约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年5月17日
收录
2026年10月1日
更新
2026年11月7日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

C - Routing

思路

广搜或最短路板子。

搜一遍或跑一遍,求出 (1,1)(1,1) 到 (N,N)(N,N) 最少经过多少蓝色,(1,N)(1,N) 到 (N,1)(N,1) 最少经过多少红色,相加即答案。这里给出最短路代码。

代码

C++
#include <bits/stdc++.h>
using namespace std;
char s[505][505];
int n, b[505][505], r[505][505];
bool vis[505][505];
int xz[] = {1, 0, -1, 0};
int yz[] = {0, 1, 0, -1};
struct node {int x, y, d;};
bool operator < (node a, node b) {
    return a.d > b.d;
}
priority_queue <node> q;
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++) scanf("%s", s[i] + 1);
    memset(b, 0x3f, sizeof(b));
    memset(r, 0x3f, sizeof(r));
    b[1][1] = (s[1][1] == 'B');
    q.push({1, 1, b[1][1]});
    while (!q.empty()) {
        node now = q.top(); q.pop();
        if (vis[now.x][now.y]) continue;
        vis[now.x][now.y] = 1;
        if (now.x == n && now.y == n) continue;
        for (int i = 0; i < 4; i ++) {
            int xx = now.x + xz[i], yy = now.y + yz[i];
            if (xx < 1 || xx > n || yy < 1 || yy > n) continue;
            if (b[xx][yy] > now.d + (s[xx][yy] == 'B')) {
                b[xx][yy] = now.d + (s[xx][yy] == 'B');
                q.push({xx, yy, b[xx][yy]}); 
            }
        }
    }
    memset(vis, 0, sizeof(vis));
    r[n][1] = (s[n][1] == 'R');
    q.push({n, 1, r[n][1]});
    while (!q.empty()) {
        node now = q.top(); q.pop();
        if (vis[now.x][now.y]) continue;
        vis[now.x][now.y] = 1;
        if (now.x == 1 && now.y == n) continue;
        for (int i = 0; i < 4; i ++) {
            int xx = now.x + xz[i], yy = now.y + yz[i];
            if (xx < 1 || xx > n || yy < 1 || yy > n) continue;
            if (r[xx][yy] > now.d + (s[xx][yy] == 'R')) {
                r[xx][yy] = now.d + (s[xx][yy] == 'R');
                q.push({xx, yy, r[xx][yy]}); 
            }
        }
    }
    printf("%d\n", b[n][n] + r[1][n]);
    return 0;
}
原文