跳到正文

题解

题解:B4224 [常州市程序设计小能手 2024] 最小值

DFLJ约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
获赞
1
题目
B4224

版本

  1. v1当前

B4224 最小值

题意:

给定 nn 个数字,用这 1010 个数字拼一个最小的质数。每个数字可以用无数次。

传送门

思路:爆搜

数据只有10个数,于是想到搜索。在每一层时考虑遍历,加上一个数,当凑出的数成为质数时,求最小值。

代码

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,a[11],ans=1e9;
bool ip(int x)//质数判断函数
{
    if(x<2) return false;
    for(int i=2; i*i<=x; i++)
    {
        if(x%i==0) return false;
    }
    return true;
}
void dfs(int step,int value)//爆搜
{
    if(step>7)//可以证明,最优解不超过7位
    {
        return ;
    }
    if(ip(value))//如果是质数
    {
        ans=min(ans,value);
        return;
    }
    for(int i=1; i<=n; i++)//搜索
    {
        if(a[i]==0) continue;
        dfs(step+1,value*10+a[i]);
    }
}
signed main()
{
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>a[i];

    }
    sort(a+1,a+n+1);
    dfs(1,0);
    if(ans!=1e9)
    {
        cout<<ans;
    }
    else
    {
        cout<<-1;
    }
    return 0;
}

PS:去年市赛原题,本人被狂虐

提交记录

原文