阿里4.1笔试第一题解法

  • 阿里4.1笔试第一题思路:
    • 从串s开始bfs搜索,看是否能搜到全0
    • 中间用map<string, int>记录搜索过的串,避免重复
#include<bits/stdc++.h>

using namespace std;
typedef long long ll;

const int maxn = 1e6+5;
const double inf = 1e12;

/*

3
01
011
00110

*/

map<string, int> mp;
queue<string> q;

int main(){
    int t;
    scanf("%d", &t);
    string s;
    while(t--){
        cin>>s;
        mp.clear();
        mp[s] = 0;
        q.push(s);
        int n = s.size();
        while(!q.empty()){
            string u = q.front();
            q.pop();
            for(int i=0; i<n; i++){
                string tmp = u;
                tmp[i] = tmp[i] == '0' ? '1' : '0';
                if(i + 1 < n){
                    tmp[i+1] = tmp[i+1] == '0' ? '1' : '0';
                }
                if(i - 1 >= 0){
                    tmp[i-1] = tmp[i-1] == '0' ? '1' : '0';
                }
                if(mp.count(tmp) == 0){
                    mp[tmp] = mp[u] + 1;
                    q.push(tmp);
                }
            }
        }
        string zero = "";
        for(int i=0; i<s.size(); i++) zero += '0';
        if(mp.count(zero) == 0){
            printf("NO\n");
        }
        else{
            printf("%d\n", mp[zero]);
        }
    } 
    return 0;
} 
#阿里实习生笔试##阿里巴巴##笔试题目#
全部评论
复杂度会不会有点高啊?能ac吗
点赞 回复
分享
发布于 2020-04-01 17:56
遍历字符串。当前1,则以右边为中心进行翻转;到最后,最后一个字符是1则输出No,否则输出次数。
点赞 回复
分享
发布于 2020-04-01 20:20
小红书
校招火热招聘中
官网直投
有个 typo? 估计是 ``mp[tmp] = mp[u] + 1`` ?
点赞 回复
分享
发布于 2020-04-01 20:28
map记录状态的变化步骤,非常棒!
点赞 回复
分享
发布于 2020-04-02 12:46

相关推荐

2 2 评论
分享
牛客网
牛客企业服务