G — money

Sample Input 1 

3
3
5 0 -5
4
-1 0 1 0
4
1 2 3 -6

Sample Output 1

1
2
3

Hint

出自:codeforces Round #353(Div.2) C Money Transfers

分析:

n个银行,最多n-1次即可将所有银行债务变为0,即按顺序从第一个开始向后一个银行转移债务即可,到第n个时所有债务必为0。

在此转移过程中可以发现任何一个为0的区间都可以减少1次转移,即该区间和为0时,右边界不需要向后一个银行继续转移债务。

数出存在多少个0区间即可得到答案为n-0区间个数。

假设区间[i,j]和为0,那么[1,i-1]的区间和与[1,j]和相同。

通过map存下区间和大小出现的次数,即可得到哪些区间为0。

但从1-n递推时是否没考虑到环?由于计算[1,x](x从1-n)的区间和并存入map中,因此存在环的情况并不影响和的出现。

(这个分析抄的别人的,我不懂......)

#include<iostream>
#include<stdio.h>
#include<map>
using namespace std;
typedef long long ll;
const int M=5e3+10;
map<ll,ll> mp;
int main()
{
	int t;
	scanf("%d",&t);
	while(t--){
		int n;
		ll a,sum=0,res=0;
		mp.clear();
		scanf("%d",&n);
		for(int i=0;i<n;i++){
			scanf("%lld",&a);
			sum+=a;
			mp[sum]++;
			res=max(res,mp[sum]);
		}
		printf("%lld\n",n-res);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41555192/article/details/82317744