快速幂取余
int quickPower(int a, int b,int k)
{
int ans = 1, base = a;
while (b > 0)
{
if (b & 1)
{
ans *= base;
ans %= k;
}
base *= base;
base %= k;
b >>= 1;
}
return ans;
}
最大公约数
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a%b);
}
判断闰年
闰年判断规则:
- 公元年分除以4不可整除,为平年。
- 公元年分除以4可整除但除以100不可整除,为闰年。
- 公元年分除以100可整除但除以400不可整除,为平年。
- 公元年分除以400可整除,为闰年。
int isLeapyear(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || year % 400 == 0)
return 1; // 是闰年返回true
return 0; // 不是闰年返回false
}
N进制转换
//将10进制数转换为任意的n进制数,返回字符串
string ten_to_n(int n, int radix) //n是待转数字,radix是指定的进制
{
string ans = "";
do {
int t = n % radix;
if (t >= 0 && t <= 9)
ans += t + '0';
else
ans += t - 10 + 'a';
n /= radix;
} while (n != 0); //使用do{}while()以防止输入为0的情况
reverse(ans.begin(), ans.end());
return ans;
}
//--------------------------------------------
//任意2 - 36进制数转化为10进制数,返回整数
int n_to_ten(string s, int radix) //s是给定的radix进制字符串
{
int ans = 0;
for (int i = 0; i < s.size(); i++)
{
char t = s[i];
if (t >= '0'&&t <= '9')
ans = ans * radix + t - '0';
else
ans = ans * radix + t - 'a' + 10;
}
return ans;
}
并查集
void init(int n)
{
for(int i = 1; i <= n; i++)
f[i] = i;
}
int find(int x)
{
if(x == f[x])
return x;//元素的父节点是他本身,那么它就是它所在集合的根节点
else
return f[x] = find(f[x]);//否则查询其父节点的父节点
}
void join(int x,int y)
{
int fx = find(x);
int fy = find(y);
if(fx != fy)
f[fy] = fx;
}
最小生成树和单源最短路径
https://blog.csdn.net/weixin_45766049/article/details/114638079
二叉树
https://blog.csdn.net/weixin_45766049/article/details/113925034
背包问题
01背包问题:
无优化
for(int i=1;i<=n;i++)
{
for(int c=0;c<=m;c++)
{
f[i][c]=f[i-1][c];
if(c>=w[i])
f[i][c]=max(f[i][c],f[i-1][c-w[i]]+v[i]);
}
}
完全背包问题:
for(int i=1;i<=n;i++)
{
for(int c=0;c<=m;c++)
{
if(c>=w[i])
f[c]=max(f[c],f[c-w[i]]+v[i]);
}
}