1. 程式人生 > >11572 - Unique Snowflakes(貪心,兩指針滑動保存子段最大長度)

11572 - Unique Snowflakes(貪心,兩指針滑動保存子段最大長度)

fort ould inf inpu 問題 ica 兩指針 rst std

Emily the entrepreneur has a cool business idea: packaging and selling snow?akes. She has devised a machine that captures snow?akes as they fall, and serializes them into a stream of snow?akes that ?ow, one by one, into a package. Once the package is full, it is closed and shipped to be sold. The marketing motto for the company is “bags of uniqueness.” To live up to the motto, every snow?ake in a package must be di?erent from the others. Unfortunately, this is easier said than done, because in reality, many of the snow?akes ?owing through the machine are identical. Emily would like to know the size of the largest possible package of unique snow?akes that can be created. The machine can start ?lling the package at any time, but once it starts, all snow?akes ?owing from the machine must go into the package until the package is completed and sealed. The package can be completed and sealed before all of the snow?akes have ?owed out of the machine.
Input
The ?rst line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer n, the number of snow?akes processed by the machine. The following n lines each contain an integer (in the range 0 to 109, inclusive) uniquely identifying a snow?ake. Two snow?akes are identi?ed by the same integer if and only if they are identical. The input will contain no more than one million total snow?akes.
Output
For each test case output a line containing single integer, the maximum number of unique snow?akes that can be in a package.
Sample Input
1 5 1 2 3 2 1
Sample Output
3

分析:

從一個有n個數的序列中,找到一個最大的子段(連續的),使得這個最大子段中沒有重復元素,輸出最大子段的長度。

註意:序列是不連續的,子段必須是連續的

做法:

對於該類段查找問題可以采用經典的滑動窗口方法,即維護一個窗口,窗口的左右邊界用兩個變量L,R代表,先增加R直到出現重復數字,再增加L,再增加R,直到R達到n

技術分享圖片

貼張圖形象得一批~

set好用!

code:

#include<stdio.h>
#include <iostream>
#include <math.h>
#include <queue>
#include<set
> using namespace std; #define max_v 1000005 int a[max_v]; int main() { set<int> s; int t,n; cin>>t; while(t--) { cin>>n; for(int i=0;i<n;i++) cin>>a[i]; s.clear(); int left=0,right=0,ans=0; while(right<n) {
while(right<n&&!s.count(a[right])) { s.insert(a[right++]); } ans=max(ans,right-left); s.erase(a[left++]); } cout<<ans<<endl; } return 0; }

11572 - Unique Snowflakes(貪心,兩指針滑動保存子段最大長度)