Blue Bridge Cup Check-in Day2


Article directory

  • Candy Sharing Game
  • mayan code

1. Candy sharing game IO link

Idea of ​​this question: This question is a simulation question. In the end, everyone needs to get the same candy. So at this time, we open an array to save each person's half of the result. Then everyone needs to get the other person's candy from the left, so the left side is It can be calculated as (n+i-1)%n. Then do a ++ operation for the person with an odd number of candies.

#include <bits/stdc++.h>

constexpr int N=110;

int n;
int c[N],tmp[N];//c[N]用来表示每个人所拥有的糖果数量,tmp[N]临时数组用来分配

bool check()
{
    for(int i=0;i<n-1;i++)
        if(c[i]!=c[i+1])//判断当前是否所有人都拥有相同的糖果
            return false;
    return true;
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);std::cout.tie(nullptr);
    
    while(std::cin>>n,n){
        int cnt=0;
        
        for(int i=0;i<n;i++) std::cin>>c[i];
        
        while(!check()){
            cnt++;
            
            for(int i=0;i<n;i++) tmp[i]=c[i]/2;//首先将所有人的糖都分一半
            
            for(int i=0;i<n;i++){
                c[i]=tmp[i]+tmp[(n+i-1)%n];
                if(c[i]%2) c[i]++;
            }
        }
        
        std::cout<<cnt<<" "<<c[0]<<std::endl;
    }
    return 0;
}

2. Mayan password IO link

 Idea of ​​this question: The idea of ​​​​this question is to solve it by BFS+hash. First, we need to add the sequence string to the queue, and use the hash table to count whether the characters after each exchange are repeated. If not, use the hash table repeatedly to make statistics. The number of operations to transform to the current string

#include <bits/stdc++.h>

int n;
std::string s;
std::unordered_map<std::string,int> hash;//利用哈希表来统计每次交换后的字符

int bfs()
{
   std::queue<std::string> q;
   q.push(s);//利用bfs的思路将当前需要进行操作的字符串加入到队列中去
   
   hash[s]=0;
   
   //进行宽搜
   while(!q.empty()){
       auto t=q.front();
       q.pop();
       
       for(int i=0;i<n-3;i++){//遍历前n-3个字符以4个字符为长度看是否满足条件
           if(t.substr(i,4)=="2012")
                return hash[t];
       }
       
       for(int i=0;i<n-1;i++){
           std::string tmp=t;//这里需要保留当前t串,是为了统计次数
           std::swap(tmp[i],tmp[i+1]);
           if(!hash.count(tmp))
           {
               hash[tmp]=hash[t]+1;
               q.push(tmp);
           }
       }
   }
   
   return -1;
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);std::cout.tie(nullptr);
    
    std::cin>>n;
    std::cin>>s;
    std::cout<<bfs()<<std::endl;
    return 0;
}

Guess you like

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