《算法笔记》6.9小节——C++标准模板库(STL)介绍->algorithm头文件下常用函数介绍

这篇博客介绍了C++标准模板库(STL)中algorithm头文件下的常见函数应用,通过三个问题——求最大最小数、全排列和数组逆置,详细讲解了如何利用STL高效地解决这些问题,并给出了样例输入输出及解题思路。特别是使用next_permutation函数实现全排列的方法被重点提及。

目录

问题 A: 求最大最小数

问题 B: 全排列

问题 C: 数组逆置


问题 A: 求最大最小数

题目描述

先输入N,表示数的个数,然后输入N个数,求这N个数的最大值和最小值。N<=10000,输入的数的绝对值不大于10^6

样例输入

4  
2 0 1 2

样例输出

2 0

题解

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <utility>
#include <algorithm>
using namespace std;
int main(){
	int N;
	while(scanf("%d", &N) != EOF){
		int a[10010];
		int i;
		for(i = 0; i < N; i++){
			scanf("%d", &a[i]);
		}
		sort(a, a + N);
		printf("%d %d\n", a[N - 1], a[0]);
	}
	return 0;
}

问题 B: 全排列

题目描述

给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。
我们假设对于小写字母有'a' < 'b' < ... < 'y' < 'z',而且给定的字符串中的字母已经按照从小到大的顺序排列。

输入

输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。

输出

输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义:
已知S = s1s2...sk , T = t1t2...tk,则S < T 等价于,存在p (1 <= p <= k),使得
s1 = t1, s2 = t2, ..., sp - 1 = tp - 1, sp < tp成立。

注意每组样例输出结束后接一个空行。

样例输入

xyz

样例输出

xyz
xzy
yxz
yzx
zxy
zyx

提示

用STL中的next_permutation会非常简洁。

题解

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <utility>
#include <algorithm>
using namespace std;
int main(){
	char s[10];
	while(gets(s) != NULL){
		int len = strlen(s);
		do{
			puts(s);
		}while(next_permutation(s, s + len));
		printf("\n");
	}
	return 0;
}

问题 C: 数组逆置

题目描述

输入一个字符串,长度小于等于200,然后将数组逆置输出。

输入

测试数据有多组,每组输入一个字符串。

输出

对于每组输入,请输出逆置后的结果。

样例输入

tianqin

样例输出

niqnait

提示

注意输入的字符串可能会有空格。

题解

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <utility>
#include <algorithm>
using namespace std;
int main(){
	char str[201];
	while(gets(str) != NULL){
		int len = strlen(str);
		reverse(str, str + len);
		puts(str);
	}
	return 0;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值