標籤:style blog color io for 資料 ar div cti
在csdn上看到這麼個題目,與友友們一起分享下,如果有別的做法,也希望能拿出來交流交流。
題目詳情
有n個小朋友站成一排(編號從0到n-1),每個小朋友有一個rating值,存放在ratings數組中。老師需要給他們分
配糖果,每個小朋友至少需要一顆糖果,對於任意相鄰的兩個小朋友i和i+1,rating值大的必須比rating值小的分
配的糖果多(rating相同的沒必要分配一樣多的糖果)。
請計算最少需要多少顆糖果,才能完成上述分配。
輸入格式:
多組資料,每組資料第一行是一個正整數n。
接下來n行,每行有1個正整數,表示每個小朋友的rating值。所有整數都不超過100000。
輸出格式:
每組資料一行,包括一個正整數,表示做少需要的糖果數。
在下的解決方案:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 分配糖果{ class Program { static void Main(string[] args) { Run(); } static int ConvertToInt(string str) { try { int number=Convert.ToInt32(str); if(number>100000) { Console.WriteLine("輸入的數字超出要求!"); Message(); } return number; } catch { Console.WriteLine("輸入字元格式設定錯誤!"); Message(); } return -1; } static void Run() { Console.Clear(); Console.Write("請輸入小朋友個數:"); int n = ConvertToInt(Console.ReadLine()); int[] ratings = new int[n]; for (int i = 0; i < n; i++) { Console.Write(string.Format("請輸入第{0}個小朋友的rating:", i + 1)); ratings[i] = ConvertToInt(Console.ReadLine()); } if (n < 0) { Console.WriteLine("您輸入的數不符合實際情況!"); } else if (n == 0) { Console.WriteLine(string.Format("需要{0}個糖果1", 0)); } else if (n == 1) { Console.WriteLine(string.Format("需要{0}個糖果2", 1)); } else { int[] candys = new int[n]; for (int i = 0; i < n; i++) { Dictionary<int, int> dic = new Dictionary<int, int>(); for (int j = 0; j < n; j++) { if (candys[j] == 0) { if (dic.Count() <= 0) { dic.Add(j, ratings[j]); } else if (ratings[j] == dic.Values.First()) { dic.Add(j, ratings[j]); } else if (ratings[j] < dic.Values.First()) { dic.Clear(); dic.Add(j, ratings[j]); } } } if (dic.Count() > 0) { foreach (var d in dic) { if (d.Key == 0) { candys[d.Key] = candys[d.Key + 1] + 1; } else if (d.Key == n - 1) { if (d.Value == ratings[d.Key-1]) { candys[d.Key] = 1; } else { candys[d.Key] = candys[d.Key - 1] + 1; } } else { if (candys[d.Key - 1] > candys[d.Key + 1]) { if (d.Value == ratings[d.Key-1]) { candys[d.Key] = candys[d.Key + 1] + 1; } else { candys[d.Key] = candys[d.Key - 1] + 1; } } else { if (d.Value == ratings[d.Key + 1]) { candys[d.Key] = candys[d.Key - 1] + 1; } else { candys[d.Key] = candys[d.Key + 1] + 1; } } } } } else { break; } } Console.WriteLine(); Console.WriteLine(string.Format("需要{0}個糖果3", candys.Sum())); } Message(); } static void Message() { Console.Write("輸入1重新遊戲,輸入其他任意鍵退出:"); string key = Console.ReadLine(); if (key == "1") { Run(); } else { Environment.Exit(0); } } }}
歡樂暑假線上編程比賽第四題:分配糖果