没灵感
考虑记忆化递归。
我们先讲解一下
AI太好用了你们知道吗
C++ map讲解
1. 是什么?
map 是C++ STL里的有序键值对容器,一个键(key)对应一个值(value),键唯一不重复,默认按键升序排序,本质就是自定义下标的动态数组。
类比:字典(拼音→汉字)、电话簿(姓名→号码)。
2. 头文件
#include <map>
3. 定义格式
map<键类型, 值类型> 变量名;
示例:
map<string,int> age; // 字符串键 → 整型值
map<int,string> id; // 整型键 → 字符串值
4. 常用操作
插入/修改元素
age["张三"]=20; // 最常用
age.insert({"李四",25});
访问元素
cout<<age["张三"]; // 输出 20
遍历元素
// 范围for(最简单)
for(auto& pair:age)
{
cout<<pair.first<<":"<<pair.second<< endl;
}
pair.first=键pair.second=值
查找元素
if(age.count("张三"))// 存在返回1,不存在返回0
{
cout<<"存在";
}
删除元素
age.erase("张三"); // 按照键删除
清空/大小
age.clear(); // 清空
age.size(); // 元素个数
5. 例子
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> score;
// 插入
score["小明"] = 90;
score["小红"] = 95;
// 遍历
for(auto& s : score) {
cout << s.first << ":" << s.second << endl;
}
return 0;
}
讲完了。
定义一个map<int,int> mp,用于存储函数值。
进入递归,如果传进来的参数 mp[x]!=0就直接返回mp[x],否则按照函数要求计算即可。
超级快,总共运算次数大致在
显然可得:
#include<bits/stdc++.h>
#define int long long
using namespace std;
map<int,int> mp;
int f(int x)
{
if(x<=1)return 1;
else
{
if(mp[x]!=0)return mp[x];
else
{
if(x%3==0)
{
mp[x]=f(x/3);
return mp[x];
}
if(x%3==1)
{
mp[x]=f(x+2)+f(x-1);
return mp[x];
}
if(x%3==2)
{
mp[x]=f(x+1)+f(x-2);
return mp[x];
}
}
}
}
signed main()
{
int x;
cin>>x;
cout<<f(x);
}
后记:不开