E - Swap Places (BFS)

题目链接:

E - Swap Places

思路:

将两个人的位置看成状态,跑dfs求最短路即可.

Code:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<unordered_map>
using namespace std;
#define x first
#define y second
#define PII pair<int,int>
#define V vector<int>
#define endl "\n"
#define init(arr,num) memset(arr,num,sizeof arr)
typedef long long ll;
typedef unsigned long long llu;
const int INF=0x3f3f3f3f;
const int N=2010,M=2*N;
int h[N],e[M],ne[M],idx;
int c[N],dp[N][N];
void add(int a,int b)
{
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void solve()
{
    idx=0;
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        h[i]=-1;
        cin>>c[i];
        for(int j=1;j<=n;j++) dp[i][j]=-1;
    }
    while(m--)
    {
        int a,b;
        cin>>a>>b;
        add(a,b);
        add(b,a);
    }
    dp[1][n]=0;
    queue<PII> q;
    q.push({1,n});
    while(q.size())
    {
        auto t=q.front();
        q.pop();
        for(int i=h[t.x];~i;i=ne[i])
            for(int j=h[t.y];~j;j=ne[j])
            {
                int a=e[i],b=e[j];
                if(c[a]==c[b]) continue;
                if(dp[a][b]==-1) 
                {
                    dp[a][b]=dp[t.x][t.y]+1;
                    q.push({a,b});
                }
            }
    }
    cout<<dp[n][1]<<endl;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int _t;
    cin>>_t;
    while(_t--) solve();
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值