您的位置:首页 > Web前端

codeforces round353 money transfer 前缀和+贪心

2016-10-07 21:40 246 查看
/*
题目描述:给定一个数列,每次可以把某个数a[i]的值转移到相邻位置i-1或i+1,其中位置1和位置n相邻,问最少移动多少次
可以使数列中所有的数都变为0

分析:对于一个含有k个数且k个数和为0的区间,只需要k-1次移动就可以把这个区间内的所有数变成0;因此,将n个数的数列
划分出的和为0的区间的个数如果是cnt的话,那么需要的移动次数就是Σ(k - 1) = n - cnt;所以,问题就变成了将n个数的序列分割
成尽量多的和为0的区间。O(n)的方法是使用前缀和维护,如果i=2和i=5处的前缀和相等,则说明3 — 5这一段的区间和为
0,某一前缀和多出现一次,说明又出现了一个区间和为0的片段;综上,出现次数最多的前缀的出现次数cnt,就是可以划分的区间
的个数,最终答案就是n - cnt
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps=1e-6;
const int maxn = 1e5 + 5 ;
LL a[maxn];
map<LL , int>mp ;
int main()
{
LL prefix = 0 ;
int n , maxv = -1 ;
scanf("%d",&n);
for(int i = 1 ; i<= n ; i++){
scanf("%lld",&a[i]);
}
for(int i = 1 ; i<= n ; i++){
prefix += a[i] ;
if(mp.find(prefix) == mp.end())
mp[prefix] = 1;
else
++mp[prefix] ;
maxv = max(maxv , mp[prefix]) ;
}
printf("%d\n", n - maxv )  ;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: