CodeForces788C【BFS】

来源:互联网 发布:2015人口普查数据 编辑:程序博客网 时间:2024/06/07 09:56

题意:

给你k个数,让你挑几个数,使得他们的平均数是n。

思路:

想了半天,想到了应该是搞一下每个数与n的差值,然后再处理,但是这个范围就蒙逼了,也看到了[-1000,1000],但是如果我说这个值我枚举到了超过1000怎么办呢。。然后就卡住了。


看了一下 http://blog.csdn.net/wchhlbt/article/details/68927002
可以BFS的时候强行不让他变大(>1000)变小(<-1000)。然后就分分钟可以搜了。
now + a[i] = 1000 + n;
now + a[i] - n = 1000

Code:(CF挂了,我也不知道能不能0.0)

#include <bits/stdc++.h>using namespace std;typedef pair<int,int> PII;typedef long long LL;//#pragma comment(linker, "/STACK:102400000,102400000")const int N=2e3+10;int cur[N],d[N],n,k;bool flag1,flag2;void input(){    int x;    scanf("%d%d",&n,&k);    memset(cur,0,sizeof(cur));    for(int i=0;i<k;i++){        scanf("%d",&x);        if(x<=n) flag1=true;        if(x>=n) flag2=true;        cur[x]=1;    }}queue<int>q;int BFS(){    memset(d,-1,sizeof(d));    d[1000]=0;    q.push(1000);    while(!q.empty()){        int now = q.front();q.pop();        for(int i=0;i<=1000;i++)        {            if(cur[i]){                if(now+i-n==1000) return d[i]=d[now]+1;                if(now+i-n>=0 && now+i-n<=2000 &&d[now+i-n]==-1){                    d[now+i-n]=d[now]+1;                    q.push(now+i-n);                }            }        }    }}int main(){    flag1=flag2=false;    input();    if(flag1&&flag2) printf("%d\n",BFS());    else puts("-1");    return 0;}
原创粉丝点击