3.16刷了5个题

基础算法总结

1.素数

思路:一开始遍历是每个数,n % i判断是不是 == 0,但是可以减小这种情况(i < sqrt(n))

bool isprime(int n)
{
   if(n <= 1) return false;

   for(int i = 2; i <= sqrt(n); i ++)
  {
       if(n % i == 0)
      {
           //素数条件
           //deng == 0;
           return false;
           break;
      }
  }
   return true;
}

2.选数

image-20220316170417730

用DFS

这个题只是选一次并没有让你输出情况,当你进行dfs的时候已经都选完了

设计dfs,考虑有加起来的总数,有加起来的总个数,还有判断递归是否完成的数

#include <iostream>
#include <algorithm>
#include<cmath>
using namespace std;

int n,k;
int a[30];
int res = 0;//答案

int check(int all)
{
   if(all <= 1)return 0;
   for(int i = 2; i <= sqrt(all); i ++)
  {
       if(all % i == 0)
      {
           return 0;
      }
  }
   return 1;
}

void dfs(int x,int all,int count)
{
   
   if(x == n || count == k)
  {
       if(count == k)
      {
           res += check(all);
      }
  }
   else
  {
       dfs(x+1,all+a[x],count + 1);//选
       dfs(x+1,all,count);//不选
  }
}

int main()
{
   cin >> n >> k;
   for(int i = 0; i < n; i ++)
  {
       cin >> a[i];
  }
   
   dfs(0,0,0);
   
   cout << res ;
   
}

3.组合数问题

也是常见的递归问题,组合数要求跟之前的数不重复,让下一回递归的数大于以前的数,也就不用搞状态数组了

#include<iostream>

using namespace std;

int n,m;
int a[50];

void dfs(int u,int pre)
{
   if(u == m + 1)
  {
       for(int i = 1; i <= m;i ++)cout << a[i] << ' ';
       
       cout << endl;
  }
   
   for(int i = pre + 1; i <= n; i ++)
  {
       a[u] = i;
       dfs(u + 1,i);
  }
}

int main()
{
   cin >> n >> m;
   
   dfs(1,0);
   //第一个代表递归层数,第二个代表要该到那个数去递归了
   
   return 0;
}

4.火星人

#include <bits/stdc++.h>
using namespace std;
int main(){
   ios::sync_with_stdio(false);
   int a[100005], n, m;
   cin >> n >> m;
   for (int i = 1; i <= n; i++) {
       cin >> a[i];
  }
   //菜鸡不会手写next_permutation()
   for (; m--;) {
       next_permutation(a + 1, a + n + 1);
  }
   for (int i = 1; i <= n; i++) {
       cout << a[i] << " ";
  }
   return 0;
}

5.回文数

#include<iostream>
#include<cmath>

using namespace std;

int a,b;

bool check(int x)
{

   int y=x,num=0;//int y=x,防止x被改变
   while (y!=0)
  {
       num=num*10+y%10;//上一次数字的记录进位再加上下一位数
       y/=10;
  }
   if (num==x) return 1;
   else return 0;
}

int hh(int x)      //判断质数的函数
{
if(x == 2) return 1;

for(int i = 2; i*i <= x; i++)
{
if(x % i == 0)
return 0;
}

return 1;
}

int main()
{
   cin >> a >> b ;
   
   for(int i = a; i <= b; i ++)
  {
       //int x = check(i);
       //cout << x;
       if(check(i)  && hh(i))
      {
           cout << i << endl;
      }
  }
}

 

posted @ 2022-03-16 20:53  爽爽子的秃头生活  阅读(75)  评论(0)    收藏  举报