分析:
这道题是典型的动态规划算法问题,在递推计算的过程中需要分块考虑,所以利用一个HashMap进行辅助处理,故递推公式为:
如果a[i]在当前块出现过,那么dp[i]=dp[i-1]+1,同时HashMap清空,将a[i]放入这个HashMap;
如果a[i]在当前块未出现过,那么dp[i]=dp[i-1],同时将a[i]放入这个HashMap;
代码如下:
1 import java.io.*; 2 import java.util.*; 3 4 public class Main { 5 static final int maxn = 100005; 6 static int T, n, d1, d2; 7 static int a[] = new int[maxn]; 8 static HashMap<Integer, Boolean> exist = new HashMap<Integer, Boolean>(); 9 public static void main(String[] args) { 10 InputReader in = new InputReader(System.in); 11 PrintWriter out = new PrintWriter(System.out); 12 T = in.nextInt(); 13 for(int kase = 1; kase <= T; kase++) { 14 d2 = 1; 15 d1 = 0; 16 n = in.nextInt(); 17 for(int i = 0; i < n; i++) { 18 a[i] = in.nextInt(); 19 } 20 exist.clear(); 21 for(int i = 0; i < n; i++) { 22 if(exist.get(a[i]) != null) { 23 exist.clear(); 24 d1 = d2 + 1; 25 exist.put(a[i], true); 26 } else { 27 exist.put(a[i], true); 28 d1 = d2; 29 } 30 d2 = d1; 31 } 32 out.println(d1); 33 } 34 out.close(); 35 36 } 37 static class InputReader { 38 public BufferedReader reader; 39 public StringTokenizer tokenizer; 40 public InputReader(InputStream stream) { 41 reader = new BufferedReader(new InputStreamReader(System.in), 32768); 42 tokenizer = null; 43 } 44 public String next() { 45 try { 46 while(tokenizer == null || !tokenizer.hasMoreTokens()) { 47 tokenizer = new StringTokenizer(reader.readLine()); 48 } 49 } catch (IOException e) { 50 throw new RuntimeException(e); 51 } 52 return tokenizer.nextToken(); 53 } 54 public int nextInt() { 55 return Integer.parseInt(next()); 56 } 57 } 58 }