习题:The Great Mixing(bfs)

题目

传送门

思路

考虑到平均数为n

即每一个数减去n之后,选出的数的平均数为0,即选出的数的求和为0

之后用bfs来暴力求解即可

这里主要考虑到搜索到的浓度实际上是只能在\(-1000到1000\)之间的,

总时间复杂度即为\(O(n^2)\)

如果你和笔者一样不想卡细节,你也可以用map,时间复杂度为\(O(n^2*log_n)\)

代码

#include<iostream>
#include<queue>
#include<map>
using namespace std;
struct node
{
    int val;
    int step;
};
int n,k;
map<int,bool> f,used;
queue<node> q;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>k;
    for(int i=1,u;i<=k;i++)
    {
        cin>>u;
        u-=n;
        if(used[u]==0)
            used[u]=1;
        if(f[u]==0)
            f[u]=1;
    }
    int tot=0;
    for(map<int,bool>::iterator it=used.begin();it!=used.end();it++)
        q.push((node){(*it).first,(*it).second});
    while(!q.empty())
    {
        node t=q.front();
        q.pop();
        if(t.val==0)
        {
            cout<<t.step;
            return 0;
        }
        for(map<int,bool>::iterator it=used.begin();it!=used.end();it++)
        {
            if(f[(*it).first+t.val]==0&&-1000<=(*it).first+t.val&&(*it).first+t.val<=1000)
            {
                f[(*it).first+t.val]=1;
                q.push((node){(*it).first+t.val,t.step+1});
            }
        }
    }
    cout<<"-1";
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/loney-s/p/13388033.html