本周由于种种原因(备考日语四级、日本語能力テストN2测试以及线上上课效率低),学习的时间略微变少了一丢丢,我还是尽量挤出时间来学习算法,本周主要学习了map和multimap的应用以及广度优先搜索和深度优先搜索,这两种搜索方式学的还不够深,做题的时候一直无法ac,本周学习我还是把map和multimap放在重点上了。
刚开始接触map的时候,感觉map非常像python中的字典(dict)。
map所需要的头文件是
#include<map>
定义方式为
map <data_type1, data_type2> map_name;
map <string, int> m
在python中,字典的定义与map相似,这让我能够很快理解map的结构与功能。
下面有几个题目:
题目描述
写代码完成下面的步骤:
- 定义一个
map<char, int>
,命名为mp
;- 输入n对字符key和正整数val,每输入一对,就令
mp[key]=val
;- 正向遍历
mp
,输出所有key
和val
。输入描述
第一行一个整数n(1≤n≤10),表示key、val的对数;
接下来n行,每行一个字符key(小写字母)和一个正整数val(1≤val≤100),用空格隔开。
输出描述
每行输出一对key和val,用空格隔开。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<map>
using namespace std;
int n;
int main() {
ios::sync_with_stdio(false);
map<char,int>mp;
cin >> n;
for (int i = 1; i <= n; i++) {
char index;
int number;
cin >> index >> number;
mp.insert(map<char, int>::value_type(index, number));
}
for (map<char, int>::iterator i = mp.begin(); i != mp.end(); i++) {
printf("%c %d\n", i->first, i -> second);
}
system("pause");
}
题目描述
写代码完成下面的步骤:
- 定义一个
map<char, int>
,命名为mp
;- 输入n对字符key和正整数val,每输入一对,就令
mp[key]=val
;- 使用
mp.find()
函数寻找一个指定的键k,如果能找到,那么输出对应的值mp[k]
,否则输出-1
。输入描述
第一行一个整数n(1≤n≤10),表示key、val的对数;
接下来n行,每行一个字符key(小写字母)和一个正整数val(1≤val≤100),用空格隔开;
最后一行给出一个字符k(小写字母),表示需要寻找的键。
输出描述
按题意输出结果。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<map>
using namespace std;
int n;
int main() {
ios::sync_with_stdio(false);
map<char,int>mp;
cin >> n;
for (int i = 1; i <= n; i++) {
char index;
int number;
cin >> index >> number;
mp.insert(map<char, int>::value_type(index, number));
}
char index;
cin >> index;
for (map<char, int>::iterator i = mp.begin(); i != mp.end(); i++) {
if (i->first == index) {
printf("%d", i->second);
return 0;
}
}
cout << -1;
system("pause");
}