您的位置:首页 > 其它

今日头条2018笔试第二题

2018-03-25 17:23 453 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: