关闭

POJ3320尺取法

161人阅读 评论(0) 收藏 举报
分类:

n个数,求最小区间覆盖着n个数中所有的不相同的数字。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) {
		new POJ3320().solve();
	}
}

class POJ3320 {
	InputReader in = new InputReader(System.in);
	PrintWriter out = new PrintWriter(System.out);
	final int N = 1000008 ;
	int[] a = new int[N] ;
	Set<Integer> set = new HashSet<Integer>() ;
	Map<Integer , Integer> map = new HashMap<Integer, Integer>() ;
	
	void solve() {
		int n = in.nextInt() , size = 0 ;
		set.clear() ;
		map.clear() ; 
		for(int i = 0 ; i < n ; i++){
		    set.add(a[i] = in.nextInt() ) ;
		}
		size = set.size() ;
		
		int start = 0 , end = 0 , sum = 0 ;
		int res = n ; 
		for(;;){
			while(end < n && sum < size){
				Integer cnt = map.get(a[end]) ;
				if(cnt == null){
					sum++ ;
				    map.put(a[end] , 1) ;
				}
				else map.put(a[end] , cnt+1) ;
				end++ ;
			}
			if(sum < size) break ; 
			res = Math.min(end - start , res) ;
			int cnt = map.get(a[start]) ; 
			if(cnt == 1){
				map.remove(a[start]) ;
			    sum-- ;
			}
			else map.put(a[start] , cnt-1) ;
			start++ ;
		}
		out.println(res) ;
		out.flush() ;
	}
}

class InputReader {
	public BufferedReader reader;
	public StringTokenizer tokenizer;

	public InputReader(InputStream stream) {
		reader = new BufferedReader(new InputStreamReader(stream), 32768);
		tokenizer = new StringTokenizer("");
	}

	private void eat(String s) {
		tokenizer = new StringTokenizer(s);
	}

	public String nextLine() {
		try {
			return reader.readLine();
		} catch (Exception e) {
			return null;
		}
	}

	public boolean hasNext() {
		while (!tokenizer.hasMoreTokens()) {
			String s = nextLine();
			if (s == null)
				return false;
			eat(s);
		}
		return true;
	}

	public String next() {
		hasNext();
		return tokenizer.nextToken();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}

	public double nextDouble() {
		return Double.parseDouble(next());
	}

	public BigInteger nextBigInteger() {
		return new BigInteger(next());
	}

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:224962次
    • 积分:9770
    • 等级:
    • 排名:第1868名
    • 原创:680篇
    • 转载:0篇
    • 译文:0篇
    • 评论:55条
    文章分类
    最新评论