Algorithm/BOJ
C#) [BOJ] 1302 베스트 셀러
HSH12345
2023. 1. 22. 12:11
1302번: 베스트셀러
첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고
www.acmicpc.net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace _230122_1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
int N = int.Parse(sr.ReadLine());
Dictionary<string, int> books = new Dictionary<string, int>();
for(int i = 0; i < N; i++)
{
StringBuilder sb = new StringBuilder();
sb.Append(sr.ReadLine());
if (books.ContainsKey(sb.ToString())) // 문자를 딕셔너리에 입력받아 같은 키값이 있으면 밸류 값을 ++
{
books[sb.ToString()] += 1;
}
else
{
books.Add(sb.ToString(), 1); // 같은 키값이 없다면 밸류값을 1로설정
}
}
var sort = from book in books
orderby book.Key descending //딕셔너리를 내림차순 정렬
select book;
int tmp = 0;
string bestSeller = "";
foreach (var element in sort)
{
if (element.Value >= tmp) //키값을 기준으로 내림차순의 딕셔너리에서 밸류값이 임시값보다 같거나 클 떄
{
tmp = element.Value;
bestSeller = element.Key; // 키값을 저장하면 항상 가장 높은 밸류값을 가지면서 오름차순으로 키값을 구할 수 있음
}
}
sw.WriteLine(bestSeller);
sr.Close();
sw.Flush();
sw.Close();
}
}
}
딕셔너리의 키값과 밸류값을 모두 오름차순으로 정렬하는 방법을 이해하면 쉬운문제이다.