d194 Unique Snowflakes

題目原文

題目說明
第一行輸入幾筆資料,第二行輸入此資料共幾片(n) 雪花,接下來 n 行代表雪花編號。
輸出可裝出最多不同雪花的數目 (需連續)。

思路
假設共 5 片雪花,編號分別是 4 1 4 2 3 5,從第一個 4 開始取,接下來是 1 和 4,碰到 4 時因為與第一個 4 編號相同,所以記下此次最多取出相異雪花數目為 2;接下來從 1 開始取,依序是 4 2 3 5,記下此次最多可取出相異數目為 5 ,並且每次取出數目時都與 max 比大小,最後傳回最大值即可。

  1. #include<iostream>
  2. using namespace std;
  3. int check(int[], int);
  4.  
  5. int main()
  6. {
  7. int t, n;
  8. scanf("%d", &t);
  9. while(t--)
  10. {
  11. scanf("%d", &n);
  12. int arr[n];
  13. for(int i = 0; i < n; i++)
  14. scanf("%d", &arr[i]);
  15. int ans;
  16. ans = check(arr, n);
  17. printf("%d\n", ans);
  18. }
  19. }
  20.  
  21. int check(int arr[], int n)
  22. {
  23. int max = 0;
  24. int count = 0;
  25. int stop = -1;
  26. for(int i = 0; i < n; i++)
  27. {
  28. for(int j = stop + 1; j < i; j++)
  29. {
  30. if(arr[j] == arr[i])
  31. {
  32. stop = j; // 利用 stop 記住
  33. i = stop + 1; // 往下一個移動
  34. if(count > max)
  35. max = count;
  36. count = 0;
  37. }
  38. }
  39. count++;
  40. }
  41. if(count > max)
  42. return count;
  43. else
  44. return max;
  45. }

留言

這個網誌中的熱門文章

機率筆記 (1)

離散數學筆記 — vertex cut

機率筆記 (4) — 隨機變數