2020 Winter Holiday [gmoj2193] [fairphoto] [prefix and + math]

Title description

Given n points, each point has a coordinate xi. Some of these points are white points and others are black points. Find the length of the longest line segment that meets the following two conditions.
Condition 1: the left and right endpoints of the line segment All must be in the given n points
Condition 2: In the given n points, the number of black points in the points contained by this line segment must be equal to the number of white points (including the left and right endpoints)

Input

Line 1: An integer n
Line 2 ... n + 1 Line: An integer xi per line, indicating the coordinates of the point, and a character ('G' for black dots, 'H' for white dots), separated by spaces ,

Output

One number per line, the length of the longest line segment

Sample input

6
4 G
10 H
7 G
16 G
1 G
3 H

Sample output

7

Data range limitation

• For 30% of the data, n <= 10 3 .
• For 100% data, n <= 10 5 , 1 <= xi <= 10 9 .

analysis

Obvious prefix sum! The black point is 1, and the white point is -1. If the sum is 0, it is a legal solution.
How to update the middle one?
In fact, just delete a paragraph so that the current point is 0.
Further reasoning: The statistical prefix and the place where it first appeared can be.
(I actually feel like this question is the longest balanced sequence)
Insert picture description here

Code on

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,b,w,ff,f[1000010],ans;
char c;
struct node
{
	int x,y;
}a[1000010];
int cmp(node l,node r)
{
	return l.x<r.x;
}
int main()
{
	freopen("fairphoto.in","r",stdin);
	freopen("fairphoto.out","w",stdout);
    cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i].x;
		cin>>c;
		if(c=='G') a[i].y=1;
		else a[i].y=-1;
	} 
	sort(a,a+n+1,cmp);
	for(int i=1;i<=n;i++)
	{
		ff+=a[i].y;
		if(ff==0)
		{
			ans=max(ans,a[i].x-a[1].x);
		}
		if(f[ff+n]==0) f[ff+n]=i;
		else ans=max(ans,a[i].x-a[f[ff+n]+1].x);
	}
	cout<<ans;
	fclose(stdin);
	fclose(stdout);
    return 0;
}

Published 110 original articles · won 100 · visited 8030

Guess you like

Origin blog.csdn.net/dglyr/article/details/104826497