今日头条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;
}
输入一个长度为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;
}
相关文章推荐
- 2018春招-今日头条笔试题-第二题(python)
- 2018今日头条笔试(第二题)
- [置顶] 今日头条2018春季校园招聘研发岗位笔试 题解 临时版
- 今日头条2018春季校园招聘研发岗位笔试编程题4
- 2018春招-今日头条笔试题-第三题(python)
- 今日头条2018春季校园招聘研发岗位笔试编程题第一、二题
- 今日头条2018实习生在线编程笔试题
- 2018春招-今日头条笔试题-第四题(python)
- 今日头条2018春季校园招聘研发岗位笔试编程题1
- 2018春招-今日头条笔试题-第一题(python)
- 2018今日头条内推笔试1
- 今日头条2018校招笔试题之字符串的问题
- 今日头条2018春招研发岗笔试题目
- 今日头条笔试8/23第二题
- 2018今日头条内推笔试2
- 今日头条2018春季校园招聘研发岗位笔试编程题2
- 今日头条2018春招笔试题js版本
- 2018今日头条3.24笔试题目2
- 20170330今日头条笔试题
- 2017年4月18日今日头条笔试原题A题