把知识点再过一遍...
01 判断质数
bool isprime(int x){
if(x == 1) return false;
if(x == 2) return true;
for(int i = 2; i <= sqrt(x); i ++){
if(x % i == 0) return false;
}
return true;
}
02 去重与排序--set
set集合特点:①互异 ②默认从大到小输出 ③用迭代器遍历
例:
Sample 1
Inputcopy | Outputcopy |
---|---|
10 20 40 32 67 40 20 89 300 400 15 | 8 15 20 32 40 67 89 300 400 |
#include <bits/stdc++.h>
using namespace std;
set<int> s;
int n;
int x;
int main()
{
cin >> n;
for(int i = 0; i < n; i ++) cin >> x, s.insert(x);
set<int> ::iterator it = s.begin();
cout << s.size()<<endl;
while(it != s.end()){
cout << *it << " ";
it ++;
}
return 0;
}
03 统计数出现次数---map
map<int, int> mp;
①默认第一个数值从小到大排序 ②迭代器遍历
#include <bits/stdc++.h>
using namespace std;
map<int, int> mp;
int n;
int x;
int main()
{
cin >> n;
for(int i = 0; i < n; i ++) cin >> x, mp[x]++;
map<int,int> ::iterator it = mp.begin();
while(it != mp.end()){
//值 与 出现次数
cout << (*it).first<<" "<< (*it).second<<endl;
it ++;
}
return 0;
}
04 回文数
判断回文数
bool ishw(int x){
int a[20], f = 1;
while(x > 0){
a[f++] = x % 10;
x /= 10;
}
for(int i = 1; i <= f/2; i ++){
if(a[i] != a[f - i]) return false;
}
return true;
}
05 queue 与 priority_queue
queue
empty判空、size大小、front队头、back队尾、push_back尾插、pop_front头删操作
函数声明 | 接口说明 |
---|---|
queue | 构造空队列 |
empty | 检测队列是否为空 |
size | 返回队列中有效数字个数 |
front | 返回队头元素的引用 |
back | 返回队尾元素的引用 |
push | 在队尾将元素入队 |
pop | 将队头元素出队列 |
priority_queue
弱排序, 从小到大
优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成堆的结构,因此priority_queue就是堆,所有需要用到堆的位置都可以考虑使用priority_queue,默认状态下为大堆
我们自己定义less和greater以控制是大堆还是小堆,封装在一个结构体中,作为priority_queue的第三个模版参数
例题:
priority_queue<int> p(nums.begin(), nums.end());
// 将优先级队列中前k-1个元素删除掉
for (int i = 0; i < k - 1; ++i)
{
p.pop();
}
return p.top();
}
合并果子---小根堆
priority_queue< int,vector<int>,greater<int> > q;//小根堆的写法注意