ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

洛谷-P4011 孤岛营救问题

2022-06-11 18:34:50  阅读:154  来源: 互联网

标签:P4011 洛谷 int 孤岛 && ay ax now bx


孤岛营救问题

bfs + 状态压缩

对钥匙的状态进行压缩,然后 bfs 剪枝搜索

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
int dp[20][20][1 << 16 | 1];
int dr[20][20][20][20];
int dor[20][20];
const int xi[4] = {0, 0, 1, -1};
const int yi[4] = {1, -1, 0, 0};
int n, m, p;

struct node
{
    int x, y, dis, status;
    node(){}
    node(int _x, int _y, int _dis, int _status){x = _x; y = _y; dis = _dis; status = _status;}
};

inline bool check(int x, int y)
{
    return x >= 1 && x <= n && y >= 1 && y <= m;
}

int bfs()
{
    int ans = n * m * 100;
    queue<node>q;
    q.push({1, 1, 0, dor[1][1]});
    while(q.size())
    {
        node now = q.front();
        q.pop();
        if(now.x == n && now.y == m)
        {
            ans = now.dis < ans ? now.dis : ans;
            continue;
        }
        int& dis = dp[now.x][now.y][now.status];
        if(dis <= now.dis) continue;
        dis = now.dis;
        for(int i=0; i<4; i++)
        {
            int xx = now.x + xi[i];
            int yy = now.y + yi[i];
            if(check(xx, yy))
            {
                int way = dr[now.x][now.y][xx][yy];
                if(way == 0 || (way > 0 && (now.status & (1 << way)) == 0)) continue;
                q.push(node(xx, yy, dis + 1, now.status | dor[xx][yy]));
            }
        }
    }
    return ans;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> p;
    for(int i=0; i<=n; i++)
        for(int j=0; j<=m; j++)
            for(int u=0; u<=n; u++)
                for(int v=0; v<=m; v++)
                    dr[i][j][u][v] = -1;
    int temp = n * m * 100;
    for(int i=0; i<=n; i++)
        for(int j=0; j<=m; j++)
            for(int u=1<<(p+2); u>=0; u--)
                dp[i][j][u] = temp;
    int k;
    cin >> k;
    while(k--)
    {
        int ax, ay, bx, by, x;
        cin >> ax >> ay >> bx >> by >> x;
        dr[ax][ay][bx][by] = x;
        dr[bx][by][ax][ay] = x;
    }
    cin >> k;
    while(k--)
    {
        int x, y, z;
        cin >> x >> y >> z;
        dor[x][y] |= 1 << z;
    }
    int ans = bfs();
    if(ans == temp)
        ans = -1;
    cout << ans << endl;
    return 0;
}

标签:P4011,洛谷,int,孤岛,&&,ay,ax,now,bx
来源: https://www.cnblogs.com/dgsvygd/p/16366468.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有