[Meter garlic off] T1853 very men and women

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

Problem-solving ideas:

In the original array, so boys 1, girls −1, so long as the prefix and find two equal position, that is contiguous subsequence of men and women are equal between them. We record the location of each prefix and the first occurrence, when the next occurrence, minus the first location is the length of

why?

Prefix and the array is provided sums[], when sums[right] == sum[left]the time, described [left+1,right]is an equal number of men and women interval, the length of the interval is right - (left + 1) +1 = right - left.

Code:

#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;

int main()
{
	int n;
	cin>>n;
	vector<int>nums(n + 1,0);
	unordered_map<int,int>hash;
	hash[0] = 0;//防止 1 0 0 1这种
	int ans = 0;
	for(int i = 1; i <= n; i++)
	{
		cin>>nums[i];
		if(nums[i] == 0)
		{
			nums[i] = -1;
		} 
		nums[i] += nums[i-1];
		if(hash.find(nums[i]) == hash.end())
		{//第一次出现
			hash[nums[i]] = i;
		}
		else if(i - hash[nums[i]] > 0 && (i - hash[nums[i]] > ans))
		{//出现过
			ans = i - hash[nums[i]];
		}
	} 
	cout<<ans;
	return 0;
}
Published 166 original articles · won praise 4 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40691051/article/details/104446671