boolIsPrimeNumber(int n){if(n <=1)returnfalse;for(int i =2; i <=sqrt(n); i++){if(n % i ==0)returnfalse;}returntrue;}
素数筛法
constint maxn =101;//表长int prime[maxn], pNum =0;//prime数组存放所有素数,pNum为素数个数
bool p[maxn]={0};//如果i为素数,则p[i]为false,否则为truevoidFind_Prime(){for(int i =2; i < maxn; i++){if(p[i]== false)//如果i是素数{
prime[pNum++]= i;//把素数i存到prime数组中for(int j = i +1; j < maxn; j+= i){//筛去所有i的倍数
p[j]= true;}}}}
日期类
intisleap(int y){if((y %4==0&& y %100!=0)|| y %400==0)return1;elsereturn0;}int month[13][2]={{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
进制转换(除基取余)
int z[40], num =0;do{
z[num++]= y % q;
y = y / q;}while(y !=0);
判断回文
bool judge(char str[]){int len =strlen(str);for(int i =0; i < len/2; i++){if(str[i]!= str[len - i -1])return false;}return true;}
区间贪心
struct interval
{int x, y;//开区间左右端点}m[110];
bool cmp(interval a, interval b){if(a.x != b.x)return a.x > b.x;//先按左端点从大到小排序elsereturn a.y < b.y;//左端点相同,按右端点从小到大排序}intmain(){freopen("in.txt","r",stdin);//freopen("out.txt", "w", stdout);int n;int i;while(scanf("%d",&n)!=EOF){if(n ==0)break;for(i =0; i < n; i++)scanf("%d %d",&m[i].x,&m[i].y);sort(m, m + n, cmp);//区间排序//ans记录不想交区间个数,last记录上一个被选中区间的左端点int ans =1, last = m[0].x;for(i =1; i < n; i++){if(m[i].y <= last)//如果该区间右端点在last左边{
last = m[i].x;//以m[i]作为新选中的区间
ans++;//不相交区间个数加1}}printf("%d\n", ans);}}
最大公约数
intgcd(int a,int b){if(b ==0)return a;elsereturngcd(b, a % b);//return !b ? a : gcd(b, a % b);//简洁写法}
最小公倍数
intlcm(int a,int b){int d =gcd(a, b);return a / d * b;}
//01背包问题//w[i]为重量,c[i]为价值,V为容量for(int i =1; i <= n; i++){for(int v = w[i]; v <= V; v++)
dp[i][v]=max(dp[i-1][v], dp[i-1][v-w[i]]+c[i]);}//进一步优化空间复杂度//边界for(v =0; v <= V; v++)
dp[v]=0;for(i =1; i <= n; i++){for(int v= V; v >= w[i]; v--)
dp[v]=max(dp[v], dp[v-w[i]]+c[i]);}
//完全背包问题//w[i]为重量,c[i]为价值,V为容量for(int i =1; i <= n; i++){for(int v = w[i]; v <= V; v++)
dp[i][v]=max(dp[i-1][v], dp[i][v-w[i]]+c[i]);//唯一区别,第二个参数为dp[i]}//进一步优化空间复杂度//边界for(v =0; v <= V; v++)
dp[v]=0;for(i =1; i <= n; i++){//区别:正向枚举for(int v = w[i]; v <= V; v++)
dp[v]=max(dp[v], dp[v-w[i]]+c[i]);}