poj - 2169 - Kingdom of Magic

本文探讨了一种解决特定类型图论问题的方法,通过构建优先队列和使用广度优先搜索(BFS)策略,实现了在有限时间内求解最短路径问题的高效算法。详细介绍了算法的具体步骤、数据结构的应用以及实例代码解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意 :n个点,m条边,无向图,有两个人开始在两个相邻的点,他们要去到另一对相邻的点,每一步后,他们的位置必须相邻,问最少需要走多少步(2人的总步数)(1-2,不能立刻2-1,即不相互走同一条路)(3 <= n <= 100,3 <= n <= 100,1 <= a1, b1 <= n, a1 != b1)。

题目链接:http://poj.org/problem?id=2169

——>>以一对相邻点为一个状态,对所有状态,从原状态开始进行bfs求最短路。这用了优先队列来更新最小值。

#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

const int maxn = 100 + 10;
const int maxp = 10000 + 10;

int G[maxn][maxn], n, m, a1, b1, a2, b2;        //G为邻接矩阵
int d[maxn][maxn];      //d[i][j]为到达组合(i, j)时最少要经过多少个组合
int step[maxn][maxn];       //总步数
bool vis[maxn][maxn];       //bfs用

struct Pair{
    int A, B;
    bool operator < (const Pair& e) const{
        return step[A][B] > step[e.A][e.B];
    }
}fa[maxn][maxn];        //fa[i][j]组合(i, j)的上一步在哪

void init(){
    memset(vis, 0, sizeof(vis));
    d[a1][b1] = 1;
    step[a1][b1] = 0;
}

void bfs(){
    init();
    priority_queue<Pair> qu;
    qu.push((Pair){a1, b1});
    vis[a1][b1] = 1;
    while(!qu.empty()){
        Pair p = qu.top(); qu.pop();
        for(int i = 1; i <= n; i++) if(G[p.A][i]){
            for(int j = 1; j <= n; j++) if(G[p.B][j] && G[i][j] && i != j){
                if(i == p.B && j == p.A) continue;
                int temp;
                if(i != p.A && j != p.B) temp = step[p.A][p.B] + 2;
                else temp = step[p.A][p.B] + 1;
                if(vis[i][j] && temp >= step[i][j]) continue;
                qu.push((Pair){i, j});
                d[i][j] = d[p.A][p.B] + 1;
                step[i][j] = temp;
                fa[i][j] = (Pair){p.A, p.B};
                vis[i][j] = 1;
            }
        }
    }
}

Pair ret[maxp];
int getRet(){
    int i = 0, x = a2, y = b2;
    while(x != a1 || y != b1){
        ret[i++] = (Pair){x, y};
        int tx = fa[x][y].A;
        int ty = fa[x][y].B;
        x = tx;
        y = ty;
    }
    ret[i++] = (Pair){a1, b1};
    return i;
}

int main()
{
    int u, v;
    while(scanf("%d%d%d%d%d%d", &n, &m, &a1, &b1, &a2, &b2) == 6){
        memset(G, 0, sizeof(G));
        for(int i = 1; i <= n; i++) G[i][i] = 1;
        for(int i = 1; i <= m; i++){
            scanf("%d%d", &u, &v);
            G[u][v] = G[v][u] = 1;
        }
        bfs();
        printf("%d %d\n", step[a2][b2], d[a2][b2]);
        int cnt = getRet();
        for(int i = cnt-1; i >= 0; i--) printf("%d %d\n", ret[i].A, ret[i].B);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值