首页 > 其他分享 >B. Solitaire

B. Solitaire

时间:2023-02-10 00:11:06浏览次数:37  
标签:int top cache Solitaire path prev true

B. Solitaire

https://codeforces.com/problemset/problem/208/B

思路

dfs+回溯 对两种操作情况进行 地毯式搜索,

找到可能的一种方法。

 

Note:

需要使用cache对已经搜索过的路径的结果,做记录, 减少重复计算。参考:

https://blog.csdn.net/soyamilk233/article/details/78057093

Code

https://codeforces.com/problemset/submission/208/192943593

#include <bits/stdc++.h>
using namespace std;


map<string, bool> cache;
map<string, bool> hit;


void print_deck(vector<pair<char,char> >& v){
    cout << "------------------- deck:" << endl;

    for(int i=0; i<v.size(); i++){
        cout << v[i].first << v[i].second << " ";
    }
    cout << endl;
}

bool match(pair<char,char> a, pair<char,char> b){
    return a.first==b.first||a.second==b.second;
}

bool dfs(vector<pair<char,char> >& v,
            int n){
    string path;
    for(int i=0; i<n; i++){
        path += v[i].first + v[i].second;
    }

    if (hit[path]){
        return cache[path];
    }

    if (n == 1){
        hit[path] = true;
        cache[path] = true;
        return true;
     }

    pair<char, char> top = v[n-1];

    if(n>=2){
        pair<char, char> prev = v[n-2];
        
        if (match(top,prev)){
            v[n-2] = top;
            
            if (dfs(v, n-1)){
                cache[path] = true;
                hit[path] = true;
                
                v[n-2] = prev;
                
                return cache[path];
            }
            
            v[n-2] = prev;
        }
    }
    
    if(n >= 4){
        pair<char, char> prev = v[n-4];
        
        if (match(top,prev)){
            v[n-4] = top;
            
            if (dfs(v, n-1)){
                cache[path] = true;
                hit[path] = true;
                
                v[n-4] = prev;

                return cache[path];
            }
            
            v[n-4] = prev;
        }
    }
    
    cache[path] = false;
    hit[path] = true;

    return cache[path];
}

int main(){
    int n;
    cin>>n;

    vector<pair<char,char> >v(n);

    for(int i=0;i<n;i++){
        cin>>v[i].second>>v[i].first;
    }
    
    cout<<(dfs(v,n)?"YES":"NO")<<endl;
}

 

标签:int,top,cache,Solitaire,path,prev,true
From: https://www.cnblogs.com/lightsong/p/17107555.html

相关文章

  • D - Takahashi's Solitaire -- ATCODER
    D-Takahashi'sSolitairehttps://atcoder.jp/contests/abc277/tasks/abc277_d 思路先计算所有的输入的和total,将输入列表首先进行排列找到所有连续段和中最大的......
  • AtCoder Beginner Contest 277 D Takahashi's Solitaire
    Takahashi'sSolitaire双指针&&尺取先排个序,然后把数组扩展到\(2\timesn\),为了处理循环的情况然后双指针跑一下,限定\(r\)扩展的条件为:当前数字等于前一个或者......
  • 【ARC068F】Solitaire(dp,计数,思维)
    首先发现那个双端队列一定长这样:也就是说,这个队列中的数先单调递减,然后再单调递增,最小值为\(1\)。现在考虑从双端队列中取数,那么当我们取到\(1\)这个数时,我们会在原......