蓝桥杯打卡Day2


文章目录

  • 糖果分享游戏
  • 玛雅人的密码

一、糖果分享游戏IO链接

本题思路:本题是一道模拟题,最终需要每个人得到相同的糖果,那么此时我们开辟一个数组用来保存每个人分一半的结果,然后每个人都需要从左边拿到对方糖果,那么左边就是可以计算为(n+i-1)%n。然后对于糖果为奇数的人进行++操作。

#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;
}

二、玛雅人的密码IO链接

 本题思路:本题思路是BFS+哈希的方式解决,首先我们需要将序列串加入到队列中,利用哈希表来统计进行每一次交换后的字符是否重复,如果不重复利用哈希表来进行统计变换到当前字符串的操作次数

#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;
}

猜你喜欢

转载自blog.csdn.net/qq_67458830/article/details/132689446
今日推荐