Blue Bridge Cup Check-in Day1

 

70530b4346544ad4821252fa57119ccc.jpeg

 


 

Article directory

  • Full arrangement
  • Eight Queens

1. Fully arranged IO links

Idea of ​​this question: This question is a classic full permutation problem, which can be solved by depth-first search.

#include <bits/stdc++.h>

constexpr int N=10;

std::string s;
std::string ans;
int n;
bool st[N];

void dfs(int u)
{
    if(u==n)
    {
        std::cout<<ans<<std::endl;
        return;
    }
    
    for(int i=0;i<n;i++){
        //如果当前字符没有遍历过,则加入到当前的字符串中去
        if(!st[i]){
            st[i]=true;
            ans.push_back(s[i]);
            dfs(u+1);//继续寻找下一个满足条件的字符
            ans.pop_back();//回溯
            st[i]=false;
        }
    }
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);std::cout.tie(nullptr);
    
    std::cin>>s;
    n=s.size();
    dfs(0);
    return 0;
}

Use the next_permutation function in the STL library to solve the full permutation problem:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string s;
    cin >> s;
    do cout << s << '\n';
    while(next_permutation(s.begin(), s.end()));

    return 0;
}

2. Eight Queens IO link

The idea of ​​​​this question: Use dfs to find 92 sets of solutions. When determining whether the point can be placed as a queen, three bool type arrays col[N], dg[N], udg[N] are used to store a certain column and a certain Direct diagonal, whether a certain sub-diagonal can be placed, so when the value is true, it cannot be placed at that point. We need an array ans to store the answer. At the same time, we have to find a way to convert the column of each queen into an int type to store it. For convenience, when we perform DFS, we can first store the answer in the path[8] array as char type, and finally convert it into int type and put it into the ans array, and finally process m queries.

#include <bits/stdc++.h>

constexpr int N=20,M=100;

int n,ans[M];//ans保存92种八皇后信息
int idx;
char path[8];
bool col[N],dg[N],udg[N];//col表示列,dg表示主对角线,udg表示副对角线

void dfs(int u)
{
    if(u==8)
    {
        ans[++idx]=atoi(path);//加入到某一种情况中
        return;
    }
    
    for(int i=0;i<8;i++){
        if(!col[i]&&!dg[u+i]&&!udg[8-u+i]){
            col[i]=dg[u+i]=udg[8-u+i]=true;
            path[u]=i+1+'0';
            dfs(u+1);
            col[i]=dg[u+i]=udg[8-u+i]=false;
        }
    }
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);std::cout.tie(nullptr);
    
    dfs(0);
    std::cin>>n;
    
    while(n--){
        int x;
        std::cin>>x;
        std::cout<<ans[x]<<std::endl;
    }
    
    return 0;
}

 

 

Guess you like

Origin blog.csdn.net/qq_67458830/article/details/132655675