今日头条2018笔试第二题

1.题意:

输入一个长度为n个a的字符串,有一下两种操作:

1. m = s, s = s * 2;

2.s = s + m;

初始状态,s = 'a', m = 'a',问至少需要多少步操作,可以得到n个a的字符串。  


2.思路:

BFS和DFS都可以,但求最少操作数,可先考虑BFS,应为当BFS第一次找到答案时一定为做少的操作情况,且DFS内存容易爆。

用pair<int, int>来表示当前的<s, m>值,并使用一个哈希表存储访问状态,以此节省运行效率。

3.代码:

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
map<pair<int,int> , int > mp;
int main()
{
    int n;
    scanf("%d",&n);
    queue<pii> q;
    q.push(make_pair(1, 1));
    mp[make_pair(1,1)]=0;
    while(!q.empty())
    {
        pii pr = q.front();q.pop();
//        printf("%d %d\n",pr.first, pr.second);
        if(pr.first == n)
        {
            printf("%d\n", mp[pr]);
            exit(0);
        }
        pii t=pr;
        t.second = t.first; t.first*=2;
        if(!mp.count(t))
        {
            q.push(t);
            mp[t] = mp[pr]+1;
        }
        t=pr;
        t.first=t.first+t.second;
        if(!mp.count(t))
        {
            q.push(t);
            mp[t] = mp[pr]+1;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值