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 比大小,最後傳回最大值即可。

#include<iostream>
using namespace std;
int check(int[], int);

int main()
{
 int t, n;
 scanf("%d", &t);     
 
 while(t--)
 {
  scanf("%d", &n);
  int arr[n];
  
  for(int i = 0; i < n; i++)
   scanf("%d", &arr[i]);
  
  int ans;
  ans = check(arr, n);
  printf("%d\n", ans);
 }
}

int check(int arr[], int n)
{
 int max = 0;
 int count = 0;
 int stop = -1;
 
 for(int i = 0; i < n; i++)
 {
  for(int j = stop + 1; j < i; j++)
  {
   if(arr[j] == arr[i])
   {
    stop = j;     // 利用 stop 記住 
    i = stop + 1;    // 往下一個移動 
    if(count > max)
     max = count;
    count = 0;
   } 
  }
  count++;
 }
 
 if(count > max)
  return count;
 else
  return max;
}

留言

這個網誌中的熱門文章

離散數學筆記 — vertex cut

機率筆記 (1)

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