codeforces Gym 100187J J. Deck Shuffling dfs

CodeForces 洗牌问题解析
本文针对 CodeForces 上的一个特定洗牌问题进行解答。问题要求判断能否通过一系列给定的洗牌操作将指定数值的牌移动到牌堆的最前面。通过构建图模型并使用 DFS 算法来解决这一问题。

题目链接:

http://codeforces.com/gym/100187/problem/J

题意:

给你一堆牌,和一些洗牌机,可以改变牌的顺序,问你能不能通过洗牌机把数字为x的牌洗到第一个位置。
样例一: 最初的牌 4 3 2 1 通过第一个洗牌机把第四个位置的x(=1)洗到第三个位置 然后 第二个洗牌机把当前在第三个位置x洗到第一个位置

题解:

建边,把洗牌机每个位置–>下一个位置(也就是这个位置的值)
跑一发dfs就好了,其实就问你第一个位置和x所在的位置是否联通

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 2e5+10;

int a[maxn],vis[maxn];
map<pair<int,int>, int> mp;
vector<int> e[maxn];
bool f;

void dfs(int x){
    if(x == 1){
        f = true;
        return ;
    }
    if(f) return ;
    if(vis[x]) return ;

    vis[x] = 1;

    for(int i=0; i<(int)e[x].size(); i++){
        if(vis[e[x][i]])
            continue;
        dfs(e[x][i]);
    }
}

int main(){
    int n = read();
    for(int i=1; i<=n; i++){
        int x = read();
        a[x] = i;
    }

    int k = read();
    for(int i=0; i<k; i++){
        for(int j=1; j<=n; j++){
            int x = read();
            // if(mp[MP(j,x)]!=1){
            //  mp[MP(j,x)] = 1;
            //  e[j].PB(x);
            // }
            e[j].PB(x);  
        }
    }

    int x = read();
    dfs(a[x]);

    if(f) puts("YES");
    else puts("NO");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值