牛客网 瞎位移群岛

5 篇文章 0 订阅
#include<iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 2e3 + 10;
int flag[N];
int id[N][N];
pair<int, int> inputs[N];
int n, m, k, s, t;
int d[4][2] = {0, 1, 0, -1, -1, 0, 1, 0};
int cnt = 20;
void bfs(int u){
    //cnt --;
    //if(cnt == 0) exit(0);
    //printf("u=%d\n", u);
    flag[u] = 1;
    queue<int> q;
    q.push(u);
    while(q.size()){
        int u = q.front(); q.pop(); flag[u] = 1;
        int x = inputs[u].first, y = inputs[u].second;
        for(int i = 0; i < 4; ++ i){
            int nx = x + d[i][0], ny = y + d[i][1];
            if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && id[nx][ny] && flag[id[nx][ny]] == 0) 
                q.push(id[nx][ny]);
        }
    }
    
}
int main(){
    //cout << "hello world";
    scanf("%d%d%d%d%d", &n, &m, &k, &s, &t);
    for(int i = 1; i <= k; ++ i){
        int x, y; scanf("%d%d", &x, &y);
        id[x][y] = i;
        inputs[i] = {x, y};
    }
    //cout << 1;
    bfs(s);
    if(flag[t]) return puts("0"), 0; //没有特判开始边界
    flag[s] = 1; 
    int T; cin >> T;
    for(int tt = 1; tt <= T; tt ++){
        int u, op; scanf("%d%d", &u, &op); op --;
        int &x = inputs[u].first, &y = inputs[u].second;
        int nx = x + d[op][0], ny = y + d[op][1];
        if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && !id[nx][ny])
        {
            id[x][y] = 0; id[nx][ny] = u;
            x = nx; y = ny;
            for(int i = 0; i < 4; ++ i){
                nx = x + d[i][0], ny = y + d[i][1];
                if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && id[nx][ny])
                {
                    int a = id[nx][ny], b = id[x][y];
                    if(flag[a] == 1 && flag[b] == 1) continue;
                    if(flag[a] == 0 && flag[b] == 0) continue;
                    if(flag[a] == 0 && flag[b] == 1) bfs(a);
                    if(flag[a] == 1 && flag[b] == 0) bfs(b);
                }
            }
        }
        if(flag[t] == 1) return printf("%d\n", tt), 0;
        //printf("flag: ");
        //for(int i = 1; i <= k; ++ i) printf("%d ", flag[i]);
        //puts(" ");
    }
    puts("-1");
    return 0;
}

时间t等于0的时候要特判一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值