21天好习惯第一期—2
——算法竞赛中较为实用的C++库函数
1.__gcd(a,b);
作用:求a和b的最大公约数。
一般让我们去求两个数的公约数我们会采用辗转相除法。
int gcd(int a,int b)
{
if(a%b==0) return b;
return gcd(b,a%b);
}
殊不知还有更加简洁的方式去求的最大公约数,那就是采用C++的库函数 __gcd(a,b);
且看例题:
题解:求a和b的最小公倍数(两数相乘除以最大公约数)的结果再加一。
AC代码如下:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
long long a,b;
cin>>a>>b;
cout<<a*b/__gcd(a,b)+1<<endl;
}
}
2.bitset<n> b(m);
作用:可实现十进制和二进制的互换,参数n表示结果为n位数,参数m为要实现装换的数。
#include <bits/stdc++.h>
using namespace std;
int main( )
{
bitset<8> b1 ( 4 );
cout << "The set of bits in bitset<8> b1( 4 ) is: ( "
<< b1 << " )." << endl;
bitset<8> b2 ( 6 );
cout << "The set of bits in bitset<8> b2( 6 ) is: ( "
<< b2 << " )." << endl;
}
//输出:The set of bits in bitset<8> b1( 4 ) is: ( 00000100 ).
//The set of bits in bitset<8> b2( 6 ) is: ( 00000110 ).
3.lower_bound (begin ,end ,val)
作用:查找有序区间[begin,end]中第一个大于等于val的位置。
4.sort(begin, end,cmp)
作用:给一个k[n]数组,sort(k+0,k+n);这是对k数组的第一个到第n-1个元素进行升序,第三个参数cmp默认为升序。
#include <bits/stdc++.h>
using namespace std;
const int N=9;
int main()
{
int a[N] = {9,8,7,6,5,4,3,2,1} ;
sort(a+0,a+N);
for(int i=0;i<N;i++)
cout<<a[i]<<" ";
return 0;
}
//输出:1 2 3 4 5 6 7 8 9
5.copy(begin,end,begin)
作用:将第一个数组的begin至end 赋值到第二个容器begin开始。
#include <bits/stdc++.h>
using namespace std;
const int N=9;
int main()
{
int a[N] = {1,2,3,4,5,6,7,8,9} ;
int b[N] = {9,8,7,6,5,4,3,2,1} ;
copy(a,a+5,b);
for(int i=0;i<N;i++)
cout<<b[i]<<" ";
return 0;
}
//输出:1 2 3 4 5 4 3 2 1
6. min
, max ,swap
函数
作用:min(a , b):求a和b的最小值,max(a , b):求a和b的最大值,swap(a , b):交换a和b的值。