跳到正文

题解

P4667 [BalticOI 2011 Day1]Switch the Lamp On

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

文章信息

收录
2026年7月16日
更新
2026年7月16日
篇幅
约 4 分钟
获赞
20
题目
P4667

版本

  1. v1当前

题目传送门

1.方法

代码
	双端队列BFS

2.思路

代码
	建一个无向图,若X到Y与原有线重合,边权为0,否则为1。(要经过一次操作),然后在无向图中求从左上到右下的最短距离。
    因为边权要么0要么1,我们可以使用双端队列BFS。如果边权为0,将要到达的点加入队首,否则加队尾。
    然后就是R+C为奇数时是无解的情况。(简单证一下)

3.代码

C++
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 500010;
int dis[510][510];
char g[510][510];
pair<int, int> q[MAXN * 2];
int r, c, head, tail;
inline bool check (int x, int y) 
{
	return x >= 0 && x <= r && y >= 0 && y <= c;
	}
inline void add (int x, int y, int v)
{
    if (dis[x][y] < 0 || v < dis[x][y])
    {
        dis[x][y] = v;
        if (head == tail || v > dis[q[head].first][q[head].second]) q[tail++] = make_pair(x, y);
        else q[--head] = make_pair(x, y);
    }
}
int main ()
{
       scanf("%d %d", &r, &c);
        if ((r + c) % 2)
        {
            for (int i = 0; i < r; i++) scanf("%s", g[i]);
           printf("NO SOLUTION\n");
        }
        else
        {
            for (int i = 0; i < r; i++) scanf("%s", g[i]);
            head = tail = MAXN; q[tail++] = make_pair(0, 0);
            memset(dis, -1, sizeof dis), dis[0][0] = 0;
            while (head != tail)
            {
                int cx = q[head].first, cy = q[head].second; ++head;
                if (check(cx - 1, cy - 1))
                {
                    if (g[cx - 1][cy - 1] == '\\') add(cx - 1, cy - 1, dis[cx][cy]);
                    else add(cx - 1, cy - 1, dis[cx][cy] + 1);
                }
                if (check(cx - 1, cy + 1))
                {
                    if (g[cx - 1][cy] == '/') add(cx - 1, cy + 1, dis[cx][cy]);
                    else add(cx - 1, cy + 1, dis[cx][cy] + 1);
                }
                if (check(cx + 1, cy - 1))
                {
                    if (g[cx][cy - 1] == '/') add(cx + 1, cy - 1, dis[cx][cy]);
                    else add(cx + 1, cy - 1, dis[cx][cy] + 1);
                }
                if (check(cx + 1, cy + 1))
                {
                    if (g[cx][cy] == '\\') add(cx + 1, cy + 1, dis[cx][cy]);
                    else add(cx + 1, cy + 1, dis[cx][cy] + 1);
                }
            }
            printf("%d\n", dis[r][c]);
        }
    return 0;
}
原文
存档评论7 条抓取于