[BFS] Codeforces Round #407 (Div. 1) 788C. The Great Mixing
2017-08-26 17:17
417 查看
题意
戳这里题解
就是给出一些数,求取最少的数使得平均数等于m。每种数无限个。用平均数的套路,吧所有数减m,题面转换成取最少的数使得加和为 0 .
然后怎么做呢?考虑答案有多大,可以发现我们随便选 ai<0<aj,有 ai∗|aj|+aj∗|ai|=0 ,|ai|+|aj| 就是一个解。所以答案一定不超过 2000 。
我们还可以发现,对于任意某个答案 x1+x2+...+xk=0, 都可以改变顺序使得前缀和的范围在 [−1000,1000]。
这样分析之后就除去了很多没用的东西,就可以直接暴力 bfs 了。
时间复杂度 O(2000∗1000)
#include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; const int maxn=2005,maxe=4000005; int n,m,a[1000005]; int fir[maxn],nxt[maxe],son[maxe],tot; void add(int x,int y){ son[++tot]=y; nxt[tot]=fir[x]; fir[x]=tot; } queue<int> que; int d[maxn]; int main(){ //freopen("cf788C.in","r",stdin); //freopen("cf788C.out","w",stdout); scanf("%d%d",&m,&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]), a[i]-=m; sort(a+1,a+1+n); n=unique(a+1,a+1+n)-(a+1); for(int i=0;i<=2000;i++) for(int j=1;j<=n;j++) if(0<=i+a[j]&&i+a[j]<=2000) add(i,i+a[j]); memset(d,63,sizeof(d)); int INF=d[0]; que.push(1000); d[1000]=0; while(!que.empty()){ int x=que.front(); que.pop(); for(int j=fir[x];j;j=nxt[j]){ if(son[j]==1000) return printf("%d\n",d[x]+1),0; if(d[son[j]]==INF) d[son[j]]=d[x]+1, que.push(son[j]); } } printf("-1\n"); return 0; }
相关文章推荐
- Codeforces Round #407 (Div. 1) C. The Great Mixing(bfs)
- codeforces 788C The Great Mixing (bitset优化dp、bfs)
- Codeforces Round #407 (Div. 2) E The Great Mixing(BFS)
- codeforces #407(div1c div 2e)The Great Mixing
- BFS (图)——Codeforces 788 C. The Great Mixing
- 【Codeforces 789E】 The Great Mixing 【数学推导+bfs】
- CF788C:The Great Mixing(背包bitset & bfs)
- CF 788C(The Great Mixing-背包)
- Codeforces Round #407 (Div. 2)-E-The Great Mixing-滚动数组或者dfs
- The Great Mixing
- Codeforces 788 C. The Great Mixing
- (codeforces) The Great Mixing
- show div and mouse can move on the div
- poj 1426 Find The Multiple (bfs 搜索)
- poj Children of the Candy Corn(BFS+DFS)
- Codeforces Round #124 (Div. 1) D. The Next Good String
- Codeforces 294E Shaass the Great 树形dp(水
- 杭电1026——Ignatius and the Princess I(BFS)
- 【Codeforces Round #427 (Div. 2) B】The number on the board
- VK Cup 2015 - Round 1 (unofficial online mirror, Div. 1 only)E---The Art of Dealing with ATM