diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..119e518 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore index 6d2922f..8c2a37a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,409 @@ -**./*.exe \ No newline at end of file +**./*.exe +**/.DS_Store +**/.vscode/ +.DS_Store + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates +**.sln +**.vcxproj +**.vcxproj.filters +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/visualstudio \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..3ad3f1f --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "files.associations": { + "**/*.html": "html", + "**/templates/**/*.html": "django-html", + "**/templates/**/*": "django-txt", + "**/requirements{/**,*}.{txt,in}": "pip-requirements", + "string": "cpp", + "iostream": "cpp" + } +} diff --git a/1541_lost_parenthesis.exe b/1541_lost_parenthesis.exe deleted file mode 100644 index 10687ff..0000000 Binary files a/1541_lost_parenthesis.exe and /dev/null differ diff --git a/18310_antena.exe b/18310_antena.exe deleted file mode 100644 index 747012c..0000000 Binary files a/18310_antena.exe and /dev/null differ diff --git a/4949_balanced_world.exe b/4949_balanced_world.exe deleted file mode 100644 index 79e2a97..0000000 Binary files a/4949_balanced_world.exe and /dev/null differ diff --git "a/KWY/week10/BJ8980_GOLD1_\355\203\235\353\260\260.java" "b/KWY/week10/BJ8980_GOLD1_\355\203\235\353\260\260.java" new file mode 100644 index 0000000..0a4e1eb --- /dev/null +++ "b/KWY/week10/BJ8980_GOLD1_\355\203\235\353\260\260.java" @@ -0,0 +1,62 @@ +package greedy; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ8980_GOLD1_택배 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int c = Integer.parseInt(st.nextToken()); + int m = Integer.parseInt(br.readLine()); + + Pack[] packs = new Pack[m]; + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int s = Integer.parseInt(st.nextToken()) - 1; + int e = Integer.parseInt(st.nextToken()) - 1; + int b = Integer.parseInt(st.nextToken()); + + packs[i] = new Pack(s, e, b); + } + Arrays.sort(packs, (p1, p2) -> p1.end - p2.end); + + int answer = 0; + int[] nums = new int[n]; + for (Pack pack : packs) { + int temp = pack.box; + for (int i = pack.start; i < pack.end; i++) { + if(nums[i] == c) { + temp = 0; + break; + } + if (nums[i] + temp > c) { + temp = c - nums[i]; + } + } + for (int i = pack.start; i < pack.end; i++) { + nums[i] += temp; + } + answer += temp; + } + + System.out.println(answer); + } +} + +class Pack { + int start; + int end; + int box; + + public Pack(int start, int end, int box) { + this.start = start; + this.end = end; + this.box = box; + } +} diff --git "a/KWY/week10/PG_LEVEL3_N1\354\271\264\353\223\234\352\262\214\354\236\204.java" "b/KWY/week10/PG_LEVEL3_N1\354\271\264\353\223\234\352\262\214\354\236\204.java" new file mode 100644 index 0000000..9f569a8 --- /dev/null +++ "b/KWY/week10/PG_LEVEL3_N1\354\271\264\353\223\234\352\262\214\354\236\204.java" @@ -0,0 +1,91 @@ +package greedy; + +import java.util.*; + +public class PG_LEVEL3_N1카드게임 { + + class Solution { + public int solution(int coin, int[] cards) { + int n = cards.length; + List handCards = new ArrayList<>(); + List drawCards = new ArrayList<>(); + for (int i = 0; i < n / 3; i++) { + handCards.add(cards[i]); + } + + int idx = n / 3; + int target = n + 1; + int answer = 1; + while (idx < n) { + // draw card + for (int i = idx; i < idx + 2; i++) { + drawCards.add(cards[i]); + } + idx += 2; + + int c1 = -1; + int c2 = -1; + int temp = Integer.MAX_VALUE; + // 손에 있는 카드로만 해결할 수 있는 경우 + for (int i = 0; i < handCards.size(); i++) { + for (int j = i + 1; j < handCards.size(); j++) { + int sum = handCards.get(i) + handCards.get(j); + if (sum == target) { + c1 = handCards.get(i); + c2 = handCards.get(j); + } + } + } + if (c1 != -1) { + handCards.remove(Integer.valueOf(c1)); + handCards.remove(Integer.valueOf(c2)); + answer++; + continue; + } + + // 카드 한장을 뽑아야 하는 경우 + if (coin >= 1 && drawCards.size() >= 1) { + for (int i = 0; i < handCards.size(); i++) { + for (int j = 0; j < drawCards.size(); j++) { + int sum = handCards.get(i) + drawCards.get(j); + if (sum == target) { + c1 = handCards.get(i); + c2 = drawCards.get(j); + } + } + } + if (c1 != -1) { + handCards.remove(Integer.valueOf(c1)); + drawCards.remove(Integer.valueOf(c2)); + answer++; + coin -= 1; + continue; + } + } + + // 카드 두장을 뽑아야 하는 경우 + if (coin >= 2 && drawCards.size() >= 2) { + for (int i = 0; i < drawCards.size(); i++) { + for (int j = i + 1; j < drawCards.size(); j++) { + int sum = drawCards.get(i) + drawCards.get(j); + if (sum == target) { + c1 = drawCards.get(i); + c2 = drawCards.get(j); + } + } + } + if (c1 != -1) { + drawCards.remove(Integer.valueOf(c1)); + drawCards.remove(Integer.valueOf(c2)); + answer++; + coin -= 2; + continue; + } + } + + break; + } + return answer; + } + } +} diff --git "a/KWY/week12/BJ17825_GOLD2_\354\243\274\354\202\254\354\234\204\354\234\267\353\206\200\354\235\264.java" "b/KWY/week12/BJ17825_GOLD2_\354\243\274\354\202\254\354\234\204\354\234\267\353\206\200\354\235\264.java" new file mode 100644 index 0000000..ee5e06a --- /dev/null +++ "b/KWY/week12/BJ17825_GOLD2_\354\243\274\354\202\254\354\234\204\354\234\267\353\206\200\354\235\264.java" @@ -0,0 +1,118 @@ +package simulation; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ17825_GOLD2_주사위윷놀이 { + /* + * 말이 이동을 마치는 칸에 다른 말이 있으면 그 말은 고를 수 없다. 단, 이동을 마치는 칸이 도착 칸이면 고를 수 있다. + * -> 이동하려는 칸에 다른 말이 있으면 해당 칸으로 이동할 수 없다. + * + * 주사위 : 10번, 말 4개 -> 모든 경우의 수 4^10 -> 완탐 + * */ + private static Place[] map; + private static int[] nums; + private static int answer = -1; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + createMap(); + + StringTokenizer st = new StringTokenizer(br.readLine()); + nums = new int[10]; + for (int i = 0; i < 10; i++) { + nums[i] = Integer.parseInt(st.nextToken()); + } + dfs(0, new int[]{0, 0, 0, 0}, new int[]{0, 0, 0, 0}); + System.out.println(answer); + } + + private static void dfs(int idx, int[] place, int[] scores) { + if (idx == 10) { + int temp = 0; + for (int score : scores) { + temp += score; + } + answer = Math.max(answer, temp); + return; + } + + for (int i = 0; i < 4; i++) { + if (place[i] == 32) { + continue; + } + + int nextPlace = map[place[i]].next[nums[idx] - 1]; + if (isPlace(place, nextPlace)) { + continue; + } + + int tempPlace = place[i]; + place[i] = nextPlace; + + int tempScore = scores[i]; + scores[i] += map[place[i]].score; + dfs(idx + 1, place, scores); + + place[i] = tempPlace; + scores[i] = tempScore; + } + } + + private static boolean isPlace(int[] place, int nextPlace) { + for (int p : place) { + if (p == 32) { + continue; + } + if (p == nextPlace) { + return true; + } + } + return false; + } + + private static void createMap() { + map = new Place[33]; + map[0] = new Place(0, 1, 2, 3, 4, 5); + for (int i = 1; i <= 20; i++) { + map[i] = new Place(i * 2, i + 1, i + 2, i + 3, i + 4, i + 5); + } + map[16] = new Place(32, 17, 18, 19, 20, 32); + map[17] = new Place(34, 18, 19, 20, 32, 32); + map[18] = new Place(36, 19, 20, 32, 32, 32); + map[19] = new Place(38, 20, 32, 32, 32, 32); + + map[5] = new Place(10, 21, 22, 23, 24, 30); + map[10] = new Place(20, 25, 26, 24, 30, 31); + map[15] = new Place(30, 27, 28, 29, 24, 30); + map[20] = new Place(40, 32, 32, 32, 32, 32); + + map[21] = new Place(13, 22, 23, 24, 30, 31); + map[22] = new Place(16, 23, 24, 30, 31, 20); + map[23] = new Place(19, 24, 30, 31, 20, 32); + map[24] = new Place(25, 30, 31, 20, 32, 32); + + map[25] = new Place(22, 26, 24, 30, 31, 20); + map[26] = new Place(24, 24, 30, 31, 20, 32); + + map[27] = new Place(28, 28, 29, 24, 30, 31); + map[28] = new Place(27, 29, 24, 30, 31, 20); + map[29] = new Place(26, 24, 30, 31, 20, 32); + + map[30] = new Place(30, 31, 20, 32, 32, 32); + map[31] = new Place(35, 20, 32, 32, 32, 32); + map[32] = new Place(0, 32, 32, 32, 32, 32); + } +} + +class Place { + int score; + int[] next; + + public Place(int score, int num1, int num2, int num3, int num4, int num5) { + this.score = score; + this.next = new int[]{num1, num2, num3, num4, num5}; + } +} diff --git "a/KWY/week12/BJ2110_GOLD4_\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.java" "b/KWY/week12/BJ2110_GOLD4_\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.java" new file mode 100644 index 0000000..fe6e17b --- /dev/null +++ "b/KWY/week12/BJ2110_GOLD4_\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.java" @@ -0,0 +1,42 @@ +package binary_search; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ2110_GOLD4_공유기설치 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int m = Integer.parseInt(st.nextToken()); + int[] nums = new int[n]; + for (int i = 0; i < n; i++) { + nums[i] = Integer.parseInt(br.readLine()); + } + Arrays.sort(nums); + + int start = 1; + int end = nums[n - 1] - nums[0]; + while (start <= end) { + int mid = (start + end) / 2; + int cnt = 1; + int temp = nums[0]; + for (int i = 1; i < n; i++) { + if (nums[i] - temp >= mid) { + temp = nums[i]; + cnt++; + } + } + if (cnt >= m) { + start = mid + 1; + } else { + end = mid - 1; + } + } + System.out.println(end); + } +} diff --git "a/KWY/week12/BJ2352_GOLD2_\353\260\230\353\217\204\354\262\264\354\204\244\352\263\204.java" "b/KWY/week12/BJ2352_GOLD2_\353\260\230\353\217\204\354\262\264\354\204\244\352\263\204.java" new file mode 100644 index 0000000..30d2bc8 --- /dev/null +++ "b/KWY/week12/BJ2352_GOLD2_\353\260\230\353\217\204\354\262\264\354\204\244\352\263\204.java" @@ -0,0 +1,84 @@ +package lis; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ2352_GOLD2_반도체설계 { + public static void main(String[] args) throws IOException { + solve2(); + } + + /* + * solve2 LIS 이분탐색 풀이 (NlogN) + * 시간 : 284ms + * */ + private static void solve2() throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + + StringTokenizer st = new StringTokenizer(br.readLine()); + int[][] nums = new int[n][]; + for (int i = 0; i < n; i++) { + nums[i] = new int[]{i + 1, Integer.parseInt(st.nextToken())}; + } + + int[] lis = new int[n + 1]; + int len = 0; + for (int i = 0; i < n; i++) { + if (nums[i][1] > lis[len]) { + len += 1; + lis[len] = nums[i][1]; + } else { + int idx = binarySearch(0, len, nums[i][1], lis); + lis[idx] = nums[i][1]; + } + } + System.out.println(len); + } + + private static int binarySearch(int left, int right, int key, int[] lis) { + while (left < right) { + int mid = (left + right) / 2; + if (lis[mid] > key) { + right = mid; + } else { + left = mid + 1; + } + } + return right; + } + + /* solve1 LIS DP 풀이 + * N^2 시 10^8이라 1초 이상이 걸리는데, 시간 제한이 2초라서 LIS 방식으로 풀었는데 맞았다. + * 시간 : 4380ms + * */ + public static void solve1() throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + + StringTokenizer st = new StringTokenizer(br.readLine()); + int[][] nums = new int[n][]; + for (int i = 0; i < n; i++) { + nums[i] = new int[]{i + 1, Integer.parseInt(st.nextToken())}; + } + + int[] dp = new int[n]; + for (int i = 0; i < n; i++) { + dp[i] = 1; + for (int j = 0; j < i; j++) { + if (nums[i][1] > nums[j][1]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + } + + int answer = -1; + for (int i : dp) { + answer = Math.max(answer, i); + } + + System.out.println(answer); + } +} diff --git "a/KWY/week13/BJ15961_GOLD4_\355\232\214\354\240\204\354\264\210\353\260\245.java" "b/KWY/week13/BJ15961_GOLD4_\355\232\214\354\240\204\354\264\210\353\260\245.java" new file mode 100644 index 0000000..aefc320 --- /dev/null +++ "b/KWY/week13/BJ15961_GOLD4_\355\232\214\354\240\204\354\264\210\353\260\245.java" @@ -0,0 +1,61 @@ +package sliding_window; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ15961_GOLD4_회전초밥 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int d = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + int c = Integer.parseInt(st.nextToken()); + + int[] nums = new int[n]; + for (int i = 0; i < n; i++) { + nums[i] = Integer.parseInt(br.readLine()); + } + + int[] cnt = new int[d + 1]; + int temp = 1; + for (int i = 0; i < k; i++) { + if (nums[i] == c) { + continue; + } + if (cnt[nums[i]] == 0) { + temp += 1; + } + cnt[nums[i]] += 1; + } + + int answer = temp; + int start = 0; + int end = k - 1; + for (int i = 0; i < n; i++) { + if (cnt[nums[start]] - 1 == 0 && nums[start] != c) { + temp -= 1; + } + if(nums[start] != c) { + cnt[nums[start]] -= 1; + } + + start = (start + 1) % n; + end = (end + 1) % n; + + if (cnt[nums[end]] == 0 && nums[end] != c) { + temp += 1; + } + if (nums[end] != c) { + cnt[nums[end]] += 1; + } + + answer = Math.max(answer, temp); + } + + System.out.println(answer); + } +} diff --git a/KWY/week13/Codility_NailingPlanks.java b/KWY/week13/Codility_NailingPlanks.java new file mode 100644 index 0000000..ac11f67 --- /dev/null +++ b/KWY/week13/Codility_NailingPlanks.java @@ -0,0 +1,125 @@ +package binary_search; + +import java.util.Arrays; + +public class Codility_NailingPlanks { + // 누적합 사용 / https://app.codility.com/demo/results/training6APYXN-H28/ + // 시작점과 끝점의 누적합의 값이 다르면 그 사이에 못이 있다는 뜻이다. + /* + * 0 1 2 3 4 5 6 7 8 9 10 + * 0 0 1 0 1 0 1 1 0 0 1 + * 0 0 1 1 2 2 3 4 4 4 5 + * + * 4~5 : [4]-> 2-1 , [5]->2 / 4~5 사이에 못이 있다. + * */ + class Solution2 { + public static int solution(int[] A, int[] B, int[] C) { + int m = C.length; + + int start = 0; + int end = m - 1; + int answer = -1; + while (start <= end) { + int mid = (start + end) / 2; + + if (check(A, B, C, mid)) { + end = mid - 1; + answer = mid + 1; + } else { + start = mid + 1; + } + } + + return answer; + } + + public static boolean check(int[] A, int[] B, int[] C, int mid) { + // each element of arrays A, B and C is an integer within the range [1..2*M] 조건 때문에 2*m + 1을 하는 것이다. + int size = 2 * C.length + 1; + int[] sum = new int[size]; + for (int i = 0; i <= mid; i++) { + ++sum[C[i]]; + } + for (int i = 1; i < size; i++) { + sum[i] += sum[i - 1]; + } + + for (int i = 0; i < A.length; i++) { + if (sum[B[i]] <= sum[A[i] - 1]) { + return false; + } + } + return true; + } + } + + class Solution1 { + // solve 1 result : https://app.codility.com/demo/results/trainingCQE4PM-5TS/ + // 하지만 해당 풀이는 시간초과가 생길 수 있다. + // [1,30,000], [2,30,000], [3,30,000] 이고, 못 위치가 [1,2,3,4....,30,000] 일 때 시간 초과가 생길 수 있지만 해당 케이스가 없어서 정답인 것이다. + public static int solution(int[] A, int[] B, int[] C) { + int n = A.length; + int m = C.length; + + int[][] c = new int[m][2]; + for (int i = 0; i < m; i++) { + c[i] = new int[]{C[i], i + 1}; + } + Arrays.sort(c, (c1, c2) -> c1[0] - c2[0]); + + int answer = -1; + for (int i = 0; i < n; i++) { + int nail = check(A[i], B[i], c, answer); + if (nail == -1) { + return -1; + } + answer = Math.max(answer, nail); + } + + return answer; + } + + public static int check(int start, int end, int[][] c, int prev) { + int left = 0; + int right = c.length - 1; + + // 가장 왼쪽에 위치한 못을 구한다. + int minIdx = -1; + while (left <= right) { + int mid = (left + right) / 2; + + if (start > c[mid][0]) { + left = mid + 1; + } else if (end < c[mid][0]) { + right = mid - 1; + } else { + right = mid - 1; + minIdx = mid; + } + } + + if (minIdx == -1) { + return -1; + } + + // 가장 왼쪽에 있는 못부터 end 까지 순회하면서 최소 인덱스를 구한다. + int min = Integer.MAX_VALUE; + for (int i = minIdx; i < c.length; i++) { + // 해당 위치가 끝점인지 확인한다. + if (c[i][0] > end) { + break; + } + + // 이전 정답보다 왼쪽에 있으면 이전 정답 값을 반환한다. + if (c[i][1] <= prev) { + return prev; + } + + min = Math.min(min, c[i][1]); + } + + return min; + } + } + +} diff --git "a/KWY/week13/PG_LEVEL3_\354\236\205\352\265\255\354\213\254\354\202\254.java" "b/KWY/week13/PG_LEVEL3_\354\236\205\352\265\255\354\213\254\354\202\254.java" new file mode 100644 index 0000000..81e3533 --- /dev/null +++ "b/KWY/week13/PG_LEVEL3_\354\236\205\352\265\255\354\213\254\354\202\254.java" @@ -0,0 +1,28 @@ +package binary_search; + +import java.util.Arrays; + +public class PG_LEVEL3_입국심사 { + class Solution { + // 심사관 : m , 고객 : n 일 때, mLog(n) 이 되어야 한다. + public long solution(int n, int[] times) { + Arrays.sort(times); + long start = times[0]; + long end = (long)times[times.length-1]*(long)n; + while(start <= end) { + long mid = (start + end) / 2; + long temp = 0; + for(int t: times) { + temp += (mid/t); + } + if(temp >= n) { + end = mid-1; + } else { + start = mid+1; + } + } + + return start; + } + } +} diff --git "a/KWY/week14/BJ2747_BRONZE2_\355\224\274\353\263\264\353\202\230\354\271\230\354\210\230.java" "b/KWY/week14/BJ2747_BRONZE2_\355\224\274\353\263\264\353\202\230\354\271\230\354\210\230.java" new file mode 100644 index 0000000..be250dd --- /dev/null +++ "b/KWY/week14/BJ2747_BRONZE2_\355\224\274\353\263\264\353\202\230\354\271\230\354\210\230.java" @@ -0,0 +1,135 @@ +package dp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ2747_BRONZE2_피보나치수 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int[] f1Call = new int[n + 1]; + int[] f2Call = new int[n + 1]; + int[] f3Call = new int[n + 1]; + + // 재귀 + System.out.println("재귀 방식 풀이 : " + f1(n, f1Call)); + printResult(f1Call); + + // top down + int[] dp = new int[n + 1]; + dp[1] = 1; + System.out.println("Top Down 방식 풀이 : " + f2(n, dp, f2Call)); + printResult(f2Call); + + // bottom up + System.out.println("Bottom Up 방식 풀이 : " + f3(n, f3Call)); + printResult(f3Call); + } + + /* + * Bottom-Up 방식 풀이 + * + * Bottom-Up 방식이란 가장 작은 문제부터 시작해서 답을 쌓아가면서 큰 문제를 해결하는 방식이다. + * 주로 반복문을 사용하고, 점화식을 찾아야한다. + * */ + public static int f3(int n, int[] f3Call) { + int[] dp = new int[n + 1]; + dp[1] = 1; + for (int i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + + f3Call[i - 1] += 1; + f3Call[i - 2] += 1; + } + f3Call[n] += 1; + return dp[n]; + } + + /* + * Top-down 방식 풀이 + * + * Top-down 방식이란 가장 큰 문제부터 시작해서 작은 문제를 차례로 해결하는 방식이다. + * 이 때, 메모이제이션을 통해서 해결한 문제를 기억했다가 재방문했을 때 추가 재귀 호출 없이 그 값을 바로 반환한다. + * 주로 재귀를 사용한다. + * */ + public static int f2(int n, int[] dp, int[] f2Call) { + f2Call[n] += 1; + if (n == 0) { + return 0; + } + if (n == 1) { + return 1; + } + if (dp[n] != 0) { + return dp[n]; + } + dp[n] = f2(n - 1, dp, f2Call) + f2(n - 2, dp, f2Call); + return dp[n]; + } + + /* + * 재귀를 이용한 풀이 + * + * https://blogfiles.pstatic.net/20160801_275/kks227_14700305083805XBuM_GIF/complexityRecursion_1.gif?type=w3840 + * */ + public static int f1(int n, int[] f1Call) { + f1Call[n] += 1; + if (n == 0) { + return 0; + } + if (n == 1) { + return 1; + } + return f1(n - 1, f1Call) + f1(n - 2, f1Call); + } + + public static void printResult(int[] result) { + for (int i = 0; i < result.length; i++) { + System.out.println("f(" + i + ") 호출 횟수 " + result[i]); + } + System.out.println("-----------------------"); + } + /* + 재귀 방식 풀이 : 55 + f(0) 호출 횟수 34 + f(1) 호출 횟수 55 + f(2) 호출 횟수 34 + f(3) 호출 횟수 21 + f(4) 호출 횟수 13 + f(5) 호출 횟수 8 + f(6) 호출 횟수 5 + f(7) 호출 횟수 3 + f(8) 호출 횟수 2 + f(9) 호출 횟수 1 + f(10) 호출 횟수 1 + ----------------------- + Top Down 방식 풀이 : 55 + f(0) 호출 횟수 1 + f(1) 호출 횟수 2 + f(2) 호출 횟수 2 + f(3) 호출 횟수 2 + f(4) 호출 횟수 2 + f(5) 호출 횟수 2 + f(6) 호출 횟수 2 + f(7) 호출 횟수 2 + f(8) 호출 횟수 2 + f(9) 호출 횟수 1 + f(10) 호출 횟수 1 + ----------------------- + Bottom Up 방식 풀이 : 55 + f(0) 호출 횟수 1 + f(1) 호출 횟수 2 + f(2) 호출 횟수 2 + f(3) 호출 횟수 2 + f(4) 호출 횟수 2 + f(5) 호출 횟수 2 + f(6) 호출 횟수 2 + f(7) 호출 횟수 2 + f(8) 호출 횟수 2 + f(9) 호출 횟수 1 + f(10) 호출 횟수 1 + ----------------------- + * */ +} diff --git "a/KWY/week14/BJ2839_SILVER4_\354\204\244\355\203\225\353\260\260\353\213\254.java" "b/KWY/week14/BJ2839_SILVER4_\354\204\244\355\203\225\353\260\260\353\213\254.java" new file mode 100644 index 0000000..fc86b2b --- /dev/null +++ "b/KWY/week14/BJ2839_SILVER4_\354\204\244\355\203\225\353\260\260\353\213\254.java" @@ -0,0 +1,33 @@ +package dp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ2839_SILVER4_설탕배달 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int[] nums = new int[n + 1]; + nums[3] = 1; + if (n >= 5) { + nums[5] = 1; + for (int i = 6; i <= n; i++) { + int n3 = nums[i - 3]; + int n5 = nums[i - 5]; + if (n3 != 0 && n5 != 0) { + nums[i] = Math.min(n3, n5) + 1; + } else if (n3 != 0) { + nums[i] = n3 + 1; + } else if (n5 != 0) { + nums[i] = n5 + 1; + } + } + } + if (nums[n] == 0) { + System.out.println(-1); + } else { + System.out.println(nums[n]); + } + } +} diff --git a/KWY/week14/Codility_GenomicRangeQuery.java b/KWY/week14/Codility_GenomicRangeQuery.java new file mode 100644 index 0000000..f8f27b1 --- /dev/null +++ b/KWY/week14/Codility_GenomicRangeQuery.java @@ -0,0 +1,54 @@ +package prefixsum; + +// result : https://app.codility.com/demo/results/training3Q6MFX-5D4/ +public class Codility_GenomicRangeQuery { + + /* + * CAGCCTA + * + * 0 1 2 3 4 5 6 7 + * A 0 0 1 1 1 1 1 2 + * C 0 1 1 1 2 3 3 3 + * G 0 0 0 1 1 1 1 1 + * T 0 0 0 0 0 0 1 0 + * + * 위와 같은 구간합을 만들어서 + * end+1 과 start의 차를 ACGT 순으로 차를 구하고, 제일 작은 값으로 갱신한다. + * */ + public int[] solution(String S, int[] P, int[] Q) { + int n = S.length(); + int[][] nums = new int[n+1][4]; + + for(int i = 1; i <= n; i++) { + for(int j = 0; j < 4; j++) { + nums[i][j] = nums[i-1][j]; + } + int currNuc = getNuCleotide(S.charAt(i-1)); + nums[i][currNuc - 1] += 1; + } + + int m = P.length; + int[] answer = new int[m]; + for(int i = 0; i < m; i++) { + int start = P[i]; + int end = Q[i]; + + for(int j = 0; j < 4; j++) { + if(nums[end+1][j] - nums[start][j] > 0) { + answer[i] = j+1; + break; + } + } + + } + + return answer; + } + + public int getNuCleotide(char c) { + if(c == 'A') return 1; + if(c == 'C') return 2; + if(c == 'G') return 3; + return 4; + } +} diff --git "a/KWY/week15/BJ1149_SILVER1_RGB\352\261\260\353\246\254.java" "b/KWY/week15/BJ1149_SILVER1_RGB\352\261\260\353\246\254.java" new file mode 100644 index 0000000..0f48ec6 --- /dev/null +++ "b/KWY/week15/BJ1149_SILVER1_RGB\352\261\260\353\246\254.java" @@ -0,0 +1,33 @@ +package dp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ1149_SILVER1_RGB거리 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int[][] nums = new int[n][3]; + + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int r = Integer.parseInt(st.nextToken()); + int g = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + nums[i] = new int[]{r, g, b}; + } + + int[][] dp = new int[n][3]; + dp[0] = new int[]{nums[0][0], nums[0][1], nums[0][2]}; + for (int i = 1; i < n; i++) { + dp[i][0] = Math.min(dp[i - 1][1], dp[i - 1][2]) + nums[i][0]; + dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][2]) + nums[i][1]; + dp[i][2] = Math.min(dp[i - 1][0], dp[i - 1][1]) + nums[i][2]; + } + int answer = Math.min(dp[n - 1][0], dp[n - 1][1]); + answer = Math.min(answer, dp[n - 1][2]); + System.out.println(answer); + } +} diff --git "a/KWY/week15/BJ11727_SILVER3_2XN\355\203\200\354\235\274\353\247\2012.java" "b/KWY/week15/BJ11727_SILVER3_2XN\355\203\200\354\235\274\353\247\2012.java" new file mode 100644 index 0000000..4d26bde --- /dev/null +++ "b/KWY/week15/BJ11727_SILVER3_2XN\355\203\200\354\235\274\353\247\2012.java" @@ -0,0 +1,46 @@ +package dp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ11727_SILVER3_2XN타일링2 { + /* + * 1: 1 + * 2: 3 + * 3: 5 + * 4: 11 + * 5: 21 + * 6: ? + * 7: ? + * 8: 171 + * + * 2 - 1 : 2 + * 3 - 2 : 2 + * 4 - 3 : 6 + * 5 - 4 : 10 + * + * n-2 번째 수에서 * 2를 더하면 되는 규칙을 파악 + * + * 6 -> 2*(11) + 21 = 43 + * 7 -> 2*(21) + 43 = 85 + * 8 -> 2*(43) + 85 = 171 + * + * 예시로 나와 있는 8까지 해당 규칙이 잘 적용되는 것을 확인 후 점화식 적용 + * + * */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + + int[] dp = new int[n + 1]; + dp[1] = 1; + if (n > 1) { + dp[2] = 3; + for (int i = 3; i <= n; i++) { + dp[i] = (2 * dp[i - 2] % 10_007 + dp[i - 1] % 10_007) % 10_007; + } + } + System.out.println(dp[n]); + } +} diff --git "a/KWY/week15/BJ2156_SILVER1_\355\217\254\353\217\204\354\243\274\354\213\234\354\213\235.java" "b/KWY/week15/BJ2156_SILVER1_\355\217\254\353\217\204\354\243\274\354\213\234\354\213\235.java" new file mode 100644 index 0000000..e45c1dc --- /dev/null +++ "b/KWY/week15/BJ2156_SILVER1_\355\217\254\353\217\204\354\243\274\354\213\234\354\213\235.java" @@ -0,0 +1,64 @@ +package dp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ2156_SILVER1_포도주시식 { + + class Main { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int[] nums = new int[n]; + for (int i = 0; i < n; i++) { + nums[i] = Integer.parseInt(br.readLine()); + } + int[] dp = new int[n + 1]; + dp[1] = nums[0]; + if(n > 1) { + dp[2] = nums[0] + nums[1]; + } + for (int i = 3; i <= n; i++) { + dp[i] = Math.max(dp[i - 1], Math.max(dp[i - 2], dp[i - 3] + nums[i - 2]) + nums[i - 1]); + } + + System.out.println(dp[n]); + } + + /* + * 2% 정답 + * + * 현재 인덱스의 순서가 1번째일 때, 2번째 일 때, 3번 째 일 때를 배열에 저장해 두고, + * 마지막에 max 값을 찾는 방식 + * + * 순서 6 10 13 9 8 1 + * 1 6 10 19 25 31 29 + * 2 0 16 23 28 33 32 + * 3 0 6 16 23 28 33 + * + * */ + private static void solve1(int n, int[] nums) { + if (n == 1) { + System.out.println(nums[0]); + } else { + int[][] dp = new int[n + 1][3]; + dp[1][0] = nums[0]; + dp[2][0] = nums[1]; + dp[2][1] = dp[1][0] + nums[1]; + dp[2][2] = dp[1][0]; + + for (int i = 3; i <= n; i++) { + for (int j = 0; j < 2; j++) { + dp[i][j] = dp[i - 1][(j + 2) % 3] + nums[i - 1]; + } + dp[i][2] = Math.max(dp[i - 1][1], dp[i - 1][2]); + } + + int answer = Math.max(dp[n][0], dp[n][1]); + answer = Math.max(answer, dp[n][2]); + System.out.println(answer); + } + } + } +} diff --git "a/KWY/week16/\355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.java" "b/KWY/week16/\355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.java" new file mode 100644 index 0000000..5e0febc --- /dev/null +++ "b/KWY/week16/\355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.java" @@ -0,0 +1,53 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +class Main { + /* + * 1: (3,6), 2: (4,8), 3: (5,12), 4: (6,13) + * + * + * 0 1 2 3 4 + * 0 0 0 0 0 0 + * 1 0 0 0 0 0 + * 2 0 0 0 0 0 + * 3 0 6 6 6 6 + * 4 0 6 8 8 8 + * 5 0 6 8 12 12 + * 6 0 6 8 12 13 + * 7 0 6 14 14 14 + * + * + * */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + int[][] nums = new int[n][2]; + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + nums[i][0] = Integer.parseInt(st.nextToken()); + nums[i][1] = Integer.parseInt(st.nextToken()); + } + + Arrays.sort(nums, (n1, n2) -> n1[0] - n2[0]); + + int[][] dp = new int[n + 1][k + 1]; + for(int j = 0 ; j< n ; j++) { + for(int i = 1 ; i<= k ; i++) { + if(nums[j][0] > i) { + dp[j+1][i] = dp[j][i]; + continue; + } + dp[j+1][i] = Math.max(dp[j][i], nums[j][1] + dp[j][i - nums[j][0]]); + } + } + + System.out.println(dp[n][k]); + } +} \ No newline at end of file diff --git "a/KWY/week16/\355\225\251\353\266\204\355\225\264.java" "b/KWY/week16/\355\225\251\353\266\204\355\225\264.java" new file mode 100644 index 0000000..320d7ad --- /dev/null +++ "b/KWY/week16/\355\225\251\353\266\204\355\225\264.java" @@ -0,0 +1,44 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +class Main { + /* + * 0 1 2 3 4 5 6 + * 1 1 1 1 1 1 1 1 + * 2 1 2 3 4 5 6 7 + * 3 1 3 6 10 15 21 28 + * 4 1 4 10 20 35 56 64 + * + * */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + + if (k == 1) { + System.out.println(1); + return; + } + + int[][] dp = new int[n + 1][k + 1]; + + for (int i = 0; i <= n; i++) { + dp[i][1] = 1; + } + for (int i = 0; i <= k; i++) { + dp[0][i] = 1; + } + + for (int i = 2; i <= k; i++) { + for (int j = 1; j <= n; j++) { + dp[j][i] = (dp[j - 1][i] % 1_000_000_000 + dp[j][i - 1] % 1_000_000_000) % 1_000_000_000; + } + } + + System.out.println(dp[n][k]); + } +} \ No newline at end of file diff --git "a/KWY/week17/\352\270\260\354\227\205\355\210\254\354\236\220.java" "b/KWY/week17/\352\270\260\354\227\205\355\210\254\354\236\220.java" new file mode 100644 index 0000000..3613e8a --- /dev/null +++ "b/KWY/week17/\352\270\260\354\227\205\355\210\254\354\236\220.java" @@ -0,0 +1,59 @@ +package dp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ2662_GOLD2_기업투자 { + /* + * 주의: '여기서 투자가는 한 기업에 돈을 나누어 투자할 수 없다' + * + * */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int m = Integer.parseInt(st.nextToken()); + int[][] nums = new int[n + 1][m + 1]; + for (int i = 1; i <= n; i++) { + st = new StringTokenizer(br.readLine()); + st.nextToken(); + for (int j = 1; j <= m; j++) { + nums[i][j] = Integer.parseInt(st.nextToken()); + } + } + + int[][] dp = new int[n + 1][m + 1]; + // dp 별 history를 저장한다. 4개의 기업이 있을 때, 각각의 기업이 얼마씩 투자했는지 나타낸다. + // A:1, B:0, C:3, D:0 => [1,0,3,0] + int[][][] history = new int[n + 1][m + 1][m + 1]; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + int temp = -1; + for (int k = 0; k <= i; k++) { + int curr = dp[k][j - 1] + nums[i - k][j]; + if (temp < curr) { + temp = curr; + + // 해당 dp의 history를 copy 한다. + for (int t = 1; t <= m; t++) { + history[i][j][t] = history[k][j - 1][t]; + } + // i-k = 현재 투자한 값 + history[i][j][j] = i - k; + } + } + dp[i][j] = temp; + } + } + + StringBuilder sb = new StringBuilder(); + sb.append(dp[n][m]).append("\n"); + for (int i = 1; i <= m; i++) { + sb.append(history[n][m][i]).append(" "); + } + System.out.println(sb); + } +} diff --git "a/KWY/week17/\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234.md" "b/KWY/week17/\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234.md" new file mode 100644 index 0000000..f09ca80 --- /dev/null +++ "b/KWY/week17/\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234.md" @@ -0,0 +1,52 @@ +- **Disjoint Set** + - 서로 공통 원소가 없는 집합을 표현하기 위한 알고리즘이다. + - S={1,2,3,4,5,6} , A={1,2} , B={3,4} , C={5,6} + +- **Union Find** + - Disjoint Set을 표현할 때 사용하는 알고리즘으로 배열을 통해 쉽게 표현할 수 있다. + + | index | 1 | 2 | 3 | 4 | 5 | 6 | + | --- | --- | --- | --- | --- | --- | --- | + | 원소 | 1 | 2 | 3 | 4 | 5 | 6 | + - Union은 두 개의 집합을 하나의 집합으로 합치고, Find는 특정 원소의 집합을 반환한다. + - **Find** + + | index | 1 | 2 | 3 | 4 | 5 | 6 | + | --- | --- | --- | --- | --- | --- | --- | + | 원소 | 1 | 1 | 3 | 2 | 5 | 6 | + - Find (1) → , Find(2) → 1 , Find(4) → 1 + + ```java + int find(int node) + if parent[node] == node return node + // 경로를 압축한다. + return parent[node] = find(parent[node]) + ``` + + | index | 1 | 2 | 3 | 4 | 5 | 6 | + | --- | --- | --- | --- | --- | --- | --- | + | 원소 | 1 | 1 | 3 | 1 | 5 | 6 | + - **Union** + - Union : 1 , 2 + + ```java + void union(int n1, int n2) + int set1 = find(n1) + int set2 = find(n2) + if set1 > set2 : parent[set2] = set1 + else parent[set1] = set2 + ``` + before + + | index | 1 | 2 | 3 | 4 | 5 | 6 | + | --- | --- | --- | --- | --- | --- | --- | + | 원소 | **1** | **6** | 3 | 1 | **5** | **5** | + after + + | index | 1 | 2 | 3 | 4 | 5 | 6 | + | --- | --- | --- | --- | --- | --- | --- | + | 원소 | **1** | 6 | 3 | 1 | **1** | 5 | + +- **Cycle 판별** + - 그래프에서 사이클이란 특정 정점에서 출발해서 다시 처음 출발했던 곳으로 되돌아가는 것을 사이클이 있다고 말한다. + - Union 작업을 하다가, 만약 **2개의 노드의 부모 노드가 같으면 사이클이 생성된 것을 알아낼 수 있다.** \ No newline at end of file diff --git "a/KWY/week18/BJ20303_GOLD3_\355\225\240\353\241\234\354\234\210\354\235\230\354\226\221\354\225\204\354\271\230.java" "b/KWY/week18/BJ20303_GOLD3_\355\225\240\353\241\234\354\234\210\354\235\230\354\226\221\354\225\204\354\271\230.java" new file mode 100644 index 0000000..0594bcf --- /dev/null +++ "b/KWY/week18/BJ20303_GOLD3_\355\225\240\353\241\234\354\234\210\354\235\230\354\226\221\354\225\204\354\271\230.java" @@ -0,0 +1,151 @@ +package dp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Queue; +import java.util.StringTokenizer; + +public class BJ20303_GOLD3_할로윈의양아치 { + /* + * union-find 알고리즘을 통해서 친구들의 집합을 구하고, 해당 집합 별 인원을 카운팅 한다. + * 1: 2명(1,3) , 2: 4명(2,5,6,10) , 4: 2명(4,9) , 7: 2명(7,8) + * + * 각 집합에서 뺏을 수 있는 사탕의 수를 dfs를 통해서 구한다. + * 1(2명): 13개 , 2(4명): 26개 , 4(2명): 24개, 7(2명): 33개 + * + * knapsack 풀이 때 사용한 dp 방식으로 최대 사탕의 수를 구한다. + * + * 집합\친구 수 : 0 1 2 3 4 5 + * 2:13 0 0 13 13 13 13 + * 4:26 0 0 13 13 26 26 + * 2:24 0 0 24 24 26 26 + * 2:33 0 0 33 33 57 57 + * + * */ + static int[] parent; + static List> graph; + static int[] candies; + static int n; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + n = Integer.parseInt(st.nextToken()); + int m = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + + candies = new int[n + 1]; + st = new StringTokenizer(br.readLine()); + for (int i = 1; i <= n; i++) { + candies[i] = Integer.parseInt(st.nextToken()); + } + + parent = new int[n + 1]; + graph = new ArrayList<>(); + for (int i = 0; i <= n; i++) { + parent[i] = i; + graph.add(new ArrayList<>()); + } + + // graph를 입력 받음과 동시에 union-find를 통해 친구들의 집합을 구한다. + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + + graph.get(a).add(b); + graph.get(b).add(a); + union(a, b); + } + + // 친구 집합 별 인원을 구한다. + Map count = new HashMap<>(); + for (int i = 1; i <= n; i++) { + int p = find(i); + int value = count.getOrDefault(p, 0) + 1; + count.put(p, value); + } + + // k 보다 이상인 집합은 건너뛰고, 각 집합 별 뺏을 수 있는 사탕의 수를 구한다. + List steals = new ArrayList<>(); + for (Entry entry : count.entrySet()) { + if (entry.getValue() >= k) { + continue; + } + steals.add(new Steal(entry.getValue(), getCandies(entry.getKey()))); + } + + // knapsack 방식으로 최대 뺏을 수 있는 사탕의 수를 구한다. + int[][] dp = new int[steals.size() + 1][k]; + for (int i = 1; i <= steals.size(); i++) { + Steal steal = steals.get(i - 1); + for (int j = 1; j < k; j++) { + if (steal.child > j) { + dp[i][j] = dp[i - 1][j]; + continue; + } + dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - steal.child] + steal.candy); + } + } + + System.out.println(dp[steals.size()][k - 1]); + } + + private static int getCandies(int parent) { + boolean[] visited = new boolean[n + 1]; + + int candy = 0; + Queue que = new LinkedList<>(); + que.add(parent); + visited[parent] = true; + while (!que.isEmpty()) { + int friend = que.poll(); + candy += candies[friend]; + + for (int next : graph.get(friend)) { + if (visited[next]) { + continue; + } + que.add(next); + visited[next] = true; + } + } + return candy; + } + + private static void union(int x, int y) { + int px = find(x); + int py = find(y); + + if (px > py) { + parent[px] = py; + } else { + parent[py] = px; + } + } + + private static int find(int child) { + if (child == parent[child]) { + return child; + } + return parent[child] = find(parent[child]); + } + + static class Steal { + int child; + int candy; + + public Steal(int child, int candy) { + this.child = child; + this.candy = candy; + } + } +} diff --git "a/KWY/week18/BJ20955_GOLD4_\353\257\274\354\204\234\354\235\230\354\235\221\352\270\211\354\210\230\354\210\240.java" "b/KWY/week18/BJ20955_GOLD4_\353\257\274\354\204\234\354\235\230\354\235\221\352\270\211\354\210\230\354\210\240.java" new file mode 100644 index 0000000..1f5864c --- /dev/null +++ "b/KWY/week18/BJ20955_GOLD4_\353\257\274\354\204\234\354\235\230\354\235\221\352\270\211\354\210\230\354\210\240.java" @@ -0,0 +1,84 @@ +package union_find; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.util.Set; +import java.util.StringTokenizer; + +public class BJ20955_GOLD4_민서의응급수술 { + + /* + 반례 + +6 10 +3 4 +1 3 +1 5 +3 5 +1 6 +3 6 +2 5 +1 2 +5 6 +2 3 + */ + + /* + * 1 2 3 4 5 6 + * 1 1 1 3 1 1 + * + * 위와 같이 4의 집합도 결국 1인데, 경로 압축을 하지 않아서 2개의 집합으로 결과가 나온다. + * 따라서 마지막에 set.add를 할 때, parent[i]가 아닌 find(i)를 통해서 해당 parent 배열을 갱신하면서 + * 자신의 집합을 add 한다. + * + * */ + static int[] parent; + static int delete = 0; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int m = Integer.parseInt(st.nextToken()); + parent = new int[n + 1]; + for (int i = 1; i <= n; i++) { + parent[i] = i; + } + + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int u = Integer.parseInt(st.nextToken()); + int v = Integer.parseInt(st.nextToken()); + + union(u, v); + } + Set set = new HashSet<>(); + for (int i = 1; i <= n; i++) { + set.add(find(i)); + } + System.out.println(set.size() - 1 + delete); + } + + private static void union(int x, int y) { + int px = find(x); + int py = find(y); + + if (px < py) { + parent[py] = px; + } else if (px > py) { + parent[px] = py; + } else { + delete++; + } + } + + private static int find(int x) { + if (parent[x] == x) { + return parent[x]; + } + return parent[x] = find(parent[x]); + } +} diff --git "a/KWY/week18/BJ4485_GOLD4_\353\205\271\354\203\211\354\230\267\354\236\205\354\235\200\354\225\240\352\260\200\354\240\244\353\213\244\354\247\200.java" "b/KWY/week18/BJ4485_GOLD4_\353\205\271\354\203\211\354\230\267\354\236\205\354\235\200\354\225\240\352\260\200\354\240\244\353\213\244\354\247\200.java" new file mode 100644 index 0000000..b7b3531 --- /dev/null +++ "b/KWY/week18/BJ4485_GOLD4_\353\205\271\354\203\211\354\230\267\354\236\205\354\235\200\354\225\240\352\260\200\354\240\244\353\213\244\354\247\200.java" @@ -0,0 +1,68 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +class Main { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + int[][] moves = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; + int c = 1; + while (true) { + int n = Integer.parseInt(br.readLine()); + if (n == 0) { + break; + } + + int[][] maps = new int[n][n]; + int[][] max = new int[n][n]; + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) { + maps[i][j] = Integer.parseInt(st.nextToken()); + max[i][j] = Integer.MAX_VALUE; + } + } + + PriorityQueue que = new PriorityQueue<>((s1, s2) -> { + return s1.w - s2.w; + }); + que.add(new Site(0, 0, maps[0][0])); + boolean[][] visited = new boolean[n][n]; + while (!que.isEmpty()) { + Site site = que.poll(); + + for (int[] move : moves) { + int row = site.r + move[0]; + int col = site.c + move[1]; + if (row < 0 || row >= n || col < 0 || col >= n || visited[row][col]) { + continue; + } + int currWeight = site.w + maps[row][col]; + if (max[row][col] > currWeight) { + max[row][col] = currWeight; + visited[row][col] = true; + que.add(new Site(row, col, currWeight)); + } + } + } + + sb.append("Problem ").append(c++).append(": ").append(max[n - 1][n - 1]).append("\n"); + } + System.out.println(sb); + } + + static class Site { + int r; + int c; + int w; + + public Site(int r, int c, int w) { + this.r = r; + this.c = c; + this.w = w; + } + } +} diff --git "a/KWY/week18/BJ6087_GOLD3_\353\240\210\354\235\264\354\240\200\355\206\265\354\213\240.java" "b/KWY/week18/BJ6087_GOLD3_\353\240\210\354\235\264\354\240\200\355\206\265\354\213\240.java" new file mode 100644 index 0000000..212f9bd --- /dev/null +++ "b/KWY/week18/BJ6087_GOLD3_\353\240\210\354\235\264\354\240\200\355\206\265\354\213\240.java" @@ -0,0 +1,121 @@ +package greedy; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +public class BJ6087_GOLD3_레이저통신 { + static class Site { + int r; + int c; + int d; + int m; + + public Site(int r, int c, int d, int m) { + this.r = r; + this.c = c; + this.d = d; + this.m = m; + } + } + + /* + * 현재 row, col, 방향, 사용한 거울의 수의 정보를 가지고 있는 Site class를 만든다. + * 1. map을 한번 순회해서 시작점과 끝점을 구한다. + * 1-1. 시작점에서 뻗을 수 있는 레이저를 pq에 추가한다. (첫 레이저는 거울을 사용하지 않기 때문에 0이다.) + * 2. pq가 empty가 될 때까지 반복을 한다. + * 2-1. visited를 통해서 현재의 row, col, 방향으로 온 적이 있는지 확인한다. + * 2-2. visited를 갱신한다. + * 2-3. 현재 위치에서 같은 방향은 거울을 추가하지 않고, 90도 방향은 (현재 사용한 거울의 수 + 1)을 한다. + * 만약 현재 위치에서 180도 방향은 갈 방법이 없기 때문에 건너뛴다. [우,하,좌,상]으로 배치해서 (n+2)%4 == n 이면 continue + * + * 주의 + * 1. visited 배열은 꼭 필요하다: 안하면 80%에서 메모리 초과가 생긴다. + * 2. visited 배열은 방향까지 고려해야 한다: (1,1)에서 사용한 거울의 수가 1인 아래 방향과 오른쪽 방향이 생길 수 있다. + * 둘 중 어느 것이 최적일지 모르기 때문에 2개 다 순회를 해봐야한다. + +해당 예시 +4 5 +C..* +...* +...* +*.** +...C + + * + * */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int w = Integer.parseInt(st.nextToken()); + int h = Integer.parseInt(st.nextToken()); + String[] map = new String[h]; + + for (int i = 0; i < h; i++) { + map[i] = br.readLine(); + } + + // "R", "D", "L", "U" + int[][] moves = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int endRow = 0; + int endCol = 0; + int[][] nums = new int[h][w]; + PriorityQueue que = new PriorityQueue<>((s1, s2) -> s1.m - s2.m); + for (int r = 0; r < h; r++) { + for (int c = 0; c < w; c++) { + nums[r][c] = Integer.MAX_VALUE; + } + } + + for (int r = 0; r < h; r++) { + for (int c = 0; c < w; c++) { + if (map[r].charAt(c) == 'C' && que.isEmpty()) { + for (int n = 0; n < 4; n++) { + int nr = r + moves[n][0]; + int nc = c + moves[n][1]; + if (nr < 0 || nr >= h || nc < 0 || nc >= w || map[nr].charAt(nc) == '*') { + continue; + } + que.add(new Site(nr, nc, n, 0)); + nums[nr][nc] = 0; + } + } + if (map[r].charAt(c) == 'C' && !que.isEmpty()) { + endRow = r; + endCol = c; + } + } + } + + boolean[][][] visited = new boolean[h][w][4]; + while (!que.isEmpty()) { + Site site = que.poll(); + if (visited[site.r][site.c][site.d]) { + continue; + } + visited[site.r][site.c][site.d] = true; + + for (int n = 0; n < 4; n++) { + int nr = site.r + moves[n][0]; + int nc = site.c + moves[n][1]; + // 180도 방향은 생길 수 없다. + if ((site.d + 2) % 4 == n || nr < 0 || nr >= h || nc < 0 || nc >= w || map[nr].charAt(nc) == '*') { + continue; + } + + if (site.d == n && nums[nr][nc] >= site.m) { + que.add(new Site(nr, nc, n, site.m)); + nums[nr][nc] = site.m; + } else if (nums[nr][nc] >= site.m + 1) { + que.add(new Site(nr, nc, n, site.m + 1)); + nums[nr][nc] = site.m + 1; + } + } + + } + + System.out.println(nums[endRow][endCol]); + } +} diff --git "a/KWY/week8/BJ1715_GOLD4_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.java" "b/KWY/week8/BJ1715_GOLD4_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.java" new file mode 100644 index 0000000..e53974a --- /dev/null +++ "b/KWY/week8/BJ1715_GOLD4_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.java" @@ -0,0 +1,30 @@ +package heap; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; + +public class BJ1715_GOLD4_카드정렬하기 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + + PriorityQueue que = new PriorityQueue<>(); + for (int i = 0; i < n; i++) { + que.add(Integer.parseInt(br.readLine())); + } + + int answer = 0; + + while (!que.isEmpty() && que.size() != 1) { + int n1 = que.poll(); + int n2 = que.poll(); + int num = n1 + n2; + answer += num; + que.add(num); + } + + System.out.println(answer); + } +} diff --git "a/KWY/week8/BJ5427_GOLD4_\353\266\210.java" "b/KWY/week8/BJ5427_GOLD4_\353\266\210.java" new file mode 100644 index 0000000..71d8e11 --- /dev/null +++ "b/KWY/week8/BJ5427_GOLD4_\353\266\210.java" @@ -0,0 +1,106 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayDeque; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.StringTokenizer; + +class Main { + static int[][] moves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int c = Integer.parseInt(st.nextToken()); + int r = Integer.parseInt(st.nextToken()); + String[] maps = new String[r]; + for (int row = 0; row < r; row++) { + maps[row] = br.readLine(); + } + + // 초반 출발점을 찾고, 초기 화재가 난 곳과 벽은 이동할 수 없으니 visited를 true로 만든다. + boolean[][] visited = new boolean[r][c]; + ArrayDeque moveQue = new ArrayDeque<>(); + ArrayDeque fireQue = new ArrayDeque<>(); + for (int row = 0; row < maps.length; row++) { + for (int col = 0; col < maps[row].length(); col++) { + if (maps[row].charAt(col) == '*') { + fireQue.add(new Site(row, col)); + visited[row][col] = true; + } else if (maps[row].charAt(col) == '@') { + moveQue.add(new Site(row, col)); + visited[row][col] = true; + } else if (maps[row].charAt(col) == '#') { + visited[row][col] = true; + } + } + } + + boolean isAns = false; + int answer = 0; + while (!moveQue.isEmpty()) { + // 불을 전파한다. + int size = fireQue.size(); + for (int j = 0; j < size; j++) { + Site fSite = fireQue.pollFirst(); + for (int[] move : moves) { + int row = fSite.r + move[0]; + int col = fSite.c + move[1]; + if (row < 0 || row >= r || col < 0 || col >= c || visited[row][col]) { + continue; + } + fireQue.addLast(new Site(row, col)); + visited[row][col] = true; + } + } + + int size2 = moveQue.size(); + answer++; + // 이동 경로를 추가한다. + for (int j = 0; j < size2; j++) { + Site site = moveQue.poll(); + for (int[] move : moves) { + int row = site.r + move[0]; + int col = site.c + move[1]; + + if (row < 0 || row >= r || col < 0 || col >= c) { + isAns = true; + break; + } + if (visited[row][col]) { + continue; + } + moveQue.add(new Site(row, col)); + visited[row][col] = true; + } + } + + if (isAns) { + sb.append(answer).append("\n"); + break; + } + } + + if (!isAns) { + sb.append("IMPOSSIBLE").append("\n"); + } + } + + System.out.println(sb); + } +} + +class Site { + int r; + int c; + + public Site(int r, int c) { + this.r = r; + this.c = c; + } +} diff --git "a/KWY/week9/BJ1052_GOLD5_\353\254\274\353\263\221.java" "b/KWY/week9/BJ1052_GOLD5_\353\254\274\353\263\221.java" new file mode 100644 index 0000000..f7094f3 --- /dev/null +++ "b/KWY/week9/BJ1052_GOLD5_\353\254\274\353\263\221.java" @@ -0,0 +1,54 @@ +package greedy; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +public class BJ1052_GOLD5_물병 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + + /* + * n = 13 이면 초기 물병 조합운 8,4,1이다. + * 이는 13(10진수) = 1101(진수) 와 같기 때문에 + * 아래와 같이 초기 물병 조합을 구한다. + * */ + int num = n; + int cnt = 1; + PriorityQueue que = new PriorityQueue<>(); + while (num != 0) { + if (num % 2 != 0) { + que.add(cnt); + } + num /= 2; + cnt *= 2; + } + + /* + * que size가 k 보다 크면 물병을 조합해야하기 때문에 + * 오름차순으로 되어 있는 que에서 2개를 숫자 2개를 poll한 다음에 + * 두 물병의 크기가 다르면, 두 물병 중 max 값으로 가기 위해 필요한 물병의 개수를 구한다. 필요한 물병의 개수 = (max - min) 1 -> 4 : 3개 필요 + * 이후 두 물병을 합친 값을 추가한다. + * */ + int answer = 0; + while (!que.isEmpty() && que.size() > k) { + int n1 = que.poll(); + int n2 = que.poll(); + + if (n1 != n2) { + int count = Math.abs(n2 - n1); + answer += count; + } + que.add(Math.max(n1, n2) * 2); + } + + System.out.println(answer); + } + +} diff --git "a/KWY/week9/BJ12764_GOLD3_\354\213\270\354\247\200\353\260\251\354\227\220\352\260\204\354\244\200\355\225\230.java" "b/KWY/week9/BJ12764_GOLD3_\354\213\270\354\247\200\353\260\251\354\227\220\352\260\204\354\244\200\355\225\230.java" new file mode 100644 index 0000000..2df2dda --- /dev/null +++ "b/KWY/week9/BJ12764_GOLD3_\354\213\270\354\247\200\353\260\251\354\227\220\352\260\204\354\244\200\355\225\230.java" @@ -0,0 +1,101 @@ +package greedy; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +/* +* 종료된 컴퓨터가 연속될 때(1,2,3), 차선의 인덱스(2,3)를 저장하지 않았다. +* pq로 저장하도록 수정 + +반례) +7 +0 20 +3 10 +5 17 +7 13 +8 15 +14 25 +16 30 + +* * */ +public class BJ12764_GOLD3_싸지방에간준하 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + // 시간을 입력 받고, 시작 시간 순으로 오름차순한다. + int n = Integer.parseInt(br.readLine()); + Time[] times = new Time[n]; + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int start = Integer.parseInt(st.nextToken()); + int end = Integer.parseInt(st.nextToken()); + times[i] = new Time(start, end); + } + Arrays.sort(times, (c1, c2) -> c1.start - c2.start); + + /* + * cnt = 최대 컴퓨터 개수를 카운팅 + * uses = 인덱스 별 컴퓨터 사용 횟수를 카운팅 + * computers = 컴퓨터 종료 시간과 컴퓨터 인덱스를 가지고 있는 pq + * emptyComputers = 사용이 끝난 컴퓨터 인덱스를 가지고 있는 pq + * */ + int cnt = 0; + int[] uses = new int[100_001]; + PriorityQueue computers = new PriorityQueue<>((c1, c2) -> c1.end - c2.end); + PriorityQueue emptyComputers = new PriorityQueue<>(); + + for (Time time : times) { + // computers pq 내에 컴퓨터가 없다면, (cnt, uses) 갱신 + if (computers.isEmpty()) { + uses[cnt] += 1; + computers.add(new Computer(cnt++, time.end)); + continue; + } + // 비어있는 자리 중 번호가 가장 작은 자리에 앉아야 하기 때문에 종료된 컴퓨터의 인덱스 갱신 + while (!computers.isEmpty() && computers.peek().end <= time.start) { + Computer computer = computers.poll(); + emptyComputers.add(computer.idx); + } + // 종료된 컴퓨터가 있다면 해당 컴퓨터 자리를 사용, 아니라면 새로운 컴퓨터 설치 + if (!emptyComputers.isEmpty()) { + int temp = emptyComputers.poll(); + uses[temp] += 1; + computers.add(new Computer(temp, time.end)); + } else { + uses[cnt] += 1; + computers.add(new Computer(cnt++, time.end)); + } + } + + StringBuilder sb = new StringBuilder(); + sb.append(cnt).append("\n"); + for (int i = 0; i < cnt; i++) { + sb.append(uses[i]).append(" "); + } + System.out.println(sb); + } +} + +class Time { + int start; + int end; + + public Time(int start, int end) { + this.start = start; + this.end = end; + } +} + +class Computer { + int idx; + int end; + + public Computer(int idx, int end) { + this.idx = idx; + this.end = end; + } +} diff --git "a/KWY/week9/BJ1781_GOLD2_\354\273\265\353\235\274\353\251\264.java" "b/KWY/week9/BJ1781_GOLD2_\354\273\265\353\235\274\353\251\264.java" new file mode 100644 index 0000000..c5889f1 --- /dev/null +++ "b/KWY/week9/BJ1781_GOLD2_\354\273\265\353\235\274\353\251\264.java" @@ -0,0 +1,118 @@ +package greedy; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +public class BJ1781_GOLD2_컵라면 { + /* + * n <= 200,000 -> NLogN + * answer <= 2^31 -> int 가능 + * + * */ + public static void main(String[] args) throws IOException { + solve2(); + } + + /* + * 반례 해결) 뒤에 것이 더 클 때, + * 4 + * 1 1 + * 2 1 + * 3 10 + * 3 10 + * + * 마감일, 마감일이 같으면 라면 개수 순으로 poll()을 하는 우선 순위 큐를 만들고 문제 정보를 우선 순위 큐에 넣는다. + * 라면 개수가 적은 순으로 출력하는 우선 순위 큐를 만들고, 푼 문제를 해당 큐에 넣는다. + * 우선 순위 큐가 빌 때까지 poll()을 하면서 아래와 같이 조건 식을 이어나간 뒤 답을 출력한다. + * 1. 현재 문제의 마감 기한이 지나지 않았다면 answer += 라면개수 + * 2. 기한이 지났고, (answer) - (풀었던 문제 중 가장 라면 개수가 작은 문제) + (현재 문제) > answer 이라면 문제를 교체한다. + * */ + private static void solve2() throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + PriorityQueue que = new PriorityQueue<>((o1, o2) -> { + if (o1.deadLine == o2.deadLine) { + return o2.count - o1.count; + } + return o1.deadLine - o2.deadLine; + }); + for (int i = 1; i <= n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int deadLine = Integer.parseInt(st.nextToken()); + int count = Integer.parseInt(st.nextToken()); + que.add(new Problem(i, deadLine, count)); + } + + PriorityQueue solved = new PriorityQueue<>((o1, o2) -> { + return o1.count - o2.count; + }); + int day = 1; + int answer = 0; + while (!que.isEmpty()) { + Problem p = que.poll(); + if (p.deadLine >= day) { + answer += p.count; + day++; + solved.add(p); + } else if (!solved.isEmpty() && answer - solved.peek().count + p.count > answer) { + answer = answer - solved.peek().count + p.count; + solved.poll(); + solved.add(p); + } + } + System.out.println(answer); + } + + + /* + * 4% 정답 + * 마감일, 마감일이 같으면 라면 개수 순으로 poll()을 하는 우선 순위 큐를 만들고 문제 정보를 우선 순위 큐에 넣는다. + * + * 우선 순위 큐가 빌 때까지 poll()을 하면서 아래와 같이 조건 식을 이어나간 뒤 답을 출력했다. + * 1. 현재 문제의 마감 기한이 지났으면 continue + * 2. 지나지 않았으면 answer += 라면개수 + * */ + private static void solve1() throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + PriorityQueue que = new PriorityQueue<>((o1, o2) -> { + if (o1.deadLine == o2.deadLine) { + return o2.count - o1.count; + } + return o1.deadLine - o2.deadLine; + }); + for (int i = 1; i <= n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int deadLine = Integer.parseInt(st.nextToken()); + int count = Integer.parseInt(st.nextToken()); + que.add(new Problem(i, deadLine, count)); + } + + int day = 1; + int answer = 0; + while (!que.isEmpty()) { + Problem p = que.poll(); + if (p.deadLine < day) { + continue; + } + answer += p.count; + day++; + } + System.out.println(answer); + } +} + +class Problem { + int idx; + int deadLine; + int count; + + public Problem(int idx, int deadLine, int count) { + this.idx = idx; + this.deadLine = deadLine; + this.count = count; + } +} diff --git a/antena.exe b/antena.exe deleted file mode 100644 index 5a9b646..0000000 Binary files a/antena.exe and /dev/null differ diff --git a/class_add_prac.exe b/class_add_prac.exe deleted file mode 100644 index 3fc9857..0000000 Binary files a/class_add_prac.exe and /dev/null differ diff --git a/gaeun/.DS_Store b/gaeun/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/gaeun/.DS_Store differ diff --git a/gaeun/.gitignore b/gaeun/.gitignore new file mode 100644 index 0000000..fb076c2 --- /dev/null +++ b/gaeun/.gitignore @@ -0,0 +1,4 @@ +*.exe +**/*.exe +.vscode/ +.vscode \ No newline at end of file diff --git a/gaeun/.vscode/c_cpp_properties.json b/gaeun/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..64e54e0 --- /dev/null +++ b/gaeun/.vscode/c_cpp_properties.json @@ -0,0 +1,16 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [], + "cStandard": "c17", + "cppStandard": "c++14", + "intelliSenseMode": "windows-gcc-x64", + "compilerPath": "C:/msys64/ucrt64/bin/gcc.exe" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/gaeun/.vscode/settings.json b/gaeun/.vscode/settings.json new file mode 100644 index 0000000..8c6d24a --- /dev/null +++ b/gaeun/.vscode/settings.json @@ -0,0 +1,96 @@ +{ + "files.associations": { + "iostream": "cpp", + "array": "cpp", + "atomic": "cpp", + "bit": "cpp", + "*.tcc": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "compare": "cpp", + "concepts": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "string": "cpp", + "unordered_map": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "initializer_list": "cpp", + "iosfwd": "cpp", + "istream": "cpp", + "limits": "cpp", + "new": "cpp", + "numbers": "cpp", + "ostream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "typeinfo": "cpp", + "unordered_set": "cpp", + "map": "cpp", + "format": "cpp", + "any": "cpp", + "barrier": "cpp", + "bitset": "cpp", + "cfenv": "cpp", + "charconv": "cpp", + "chrono": "cpp", + "cinttypes": "cpp", + "codecvt": "cpp", + "complex": "cpp", + "condition_variable": "cpp", + "coroutine": "cpp", + "csetjmp": "cpp", + "csignal": "cpp", + "cstdarg": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cuchar": "cpp", + "forward_list": "cpp", + "list": "cpp", + "set": "cpp", + "expected": "cpp", + "ratio": "cpp", + "regex": "cpp", + "source_location": "cpp", + "fstream": "cpp", + "future": "cpp", + "iomanip": "cpp", + "latch": "cpp", + "mutex": "cpp", + "ranges": "cpp", + "scoped_allocator": "cpp", + "semaphore": "cpp", + "shared_mutex": "cpp", + "span": "cpp", + "spanstream": "cpp", + "sstream": "cpp", + "stacktrace": "cpp", + "stdfloat": "cpp", + "stop_token": "cpp", + "syncstream": "cpp", + "thread": "cpp", + "typeindex": "cpp", + "valarray": "cpp", + "variant": "cpp" + }, + "C_Cpp.default.compilerPath": "C:\\msys64\\ucrt64\\bin\\g++.exe" +} \ No newline at end of file diff --git a/gaeun/.vscode/tasks.json b/gaeun/.vscode/tasks.json new file mode 100644 index 0000000..2412227 --- /dev/null +++ b/gaeun/.vscode/tasks.json @@ -0,0 +1,109 @@ +{ + "version": "2.0.0", + "runner": "terminal", + "type": "shell", + "echoCommand": true, + "presentation": { + "reveal": "always" + }, + "tasks": [ + { + "label": "save and compile for C++", + "command": "g++", + "args": [ + "${file}", + "-o", + "-g", + "${fileDirname}/${fileBasenameNoExtension}.exe" + ], + "group": "build", + "problemMatcher": { + "fileLocation": [ + "relative", + "${workspaceRoot}" + ], + "pattern": { + "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + } + }, + { + "label": "save and compile for C", + "command": "gcc", + "args": [ + "${file}", + "-o", + "-g", + "${fileDirname}/${fileBasenameNoExtension}.exe" + ], + "group": "build", + "problemMatcher": { + "fileLocation": [ + "relative", + "${workspaceRoot}" + ], + "pattern": { + "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + } + }, + { + "label": "execute", + "command": "cd ${fileDirname} &&./${fileBasenameNoExtension}.exe", + "group": "test" + }, + { + "type": "cppbuild", + "label": "C/C++: g++ build active file", + "command": "/usr/bin/g++", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}/${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${fileDirname}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": "build", + "detail": "Task generated by Debugger." + }, + { + "type": "cppbuild", + "label": "C/C++: g++.exe build active file", + "command": "C:\\msys64\\ucrt64\\bin\\g++.exe", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "C:\\msys64\\ucrt64\\bin" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "detail": "Task generated by Debugger." + } + ] +} \ No newline at end of file diff --git a/01_variable_type.cpp b/gaeun/00_prac/01_variable_type.cpp similarity index 100% rename from 01_variable_type.cpp rename to gaeun/00_prac/01_variable_type.cpp diff --git a/02_stream.cpp b/gaeun/00_prac/02_stream.cpp similarity index 100% rename from 02_stream.cpp rename to gaeun/00_prac/02_stream.cpp diff --git a/calc_string_eq.cpp b/gaeun/00_prac/calc_string_eq.cpp similarity index 100% rename from calc_string_eq.cpp rename to gaeun/00_prac/calc_string_eq.cpp diff --git a/class_add_prac.cpp b/gaeun/00_prac/class_add_prac.cpp similarity index 100% rename from class_add_prac.cpp rename to gaeun/00_prac/class_add_prac.cpp diff --git a/hello.cpp b/gaeun/00_prac/hello.cpp similarity index 100% rename from hello.cpp rename to gaeun/00_prac/hello.cpp diff --git a/1449_repair_hangseung.cpp b/gaeun/01_greedy/1449_repair_hangseung.cpp similarity index 100% rename from 1449_repair_hangseung.cpp rename to gaeun/01_greedy/1449_repair_hangseung.cpp diff --git a/1541_lost_parenthesis.cpp b/gaeun/01_greedy/1541_lost_parenthesis.cpp similarity index 100% rename from 1541_lost_parenthesis.cpp rename to gaeun/01_greedy/1541_lost_parenthesis.cpp diff --git a/18310_antena.cpp b/gaeun/01_greedy/18310_antena.cpp similarity index 100% rename from 18310_antena.cpp rename to gaeun/01_greedy/18310_antena.cpp diff --git a/gaeun/02_stack_queue/2164_card2.cpp b/gaeun/02_stack_queue/2164_card2.cpp new file mode 100644 index 0000000..30d776a --- /dev/null +++ b/gaeun/02_stack_queue/2164_card2.cpp @@ -0,0 +1,23 @@ +#include +#include +using namespace std; + +int main(){ + int cardNum; + int goBehindNum; + queue qCard; + + cin >> cardNum; + for(int i=1; i<= cardNum; i++){ + qCard.push(i); + } + for(int i=1; i 반복 시 flag=true 안해줬었다 +*/ + + #include #include using namespace std; @@ -13,6 +18,7 @@ int main(){ stack c1; for(int i=0; i +using namespace std; + +void whatIsRecursion(int recurNum, int globRecurNum){ + int totRecurNum = globRecurNum; + int currRecurNum = recurNum; + string underscore = ""; + + for(int i = 0; i < 4 * (totRecurNum - currRecurNum); i++){ + underscore += "_"; + } + + if(recurNum == 0){ + cout << underscore << "\"재귀함수가 뭔가요?\"\n"; + cout << underscore << "\"재귀함수는 자기 자신을 호출하는 함수라네\"\n"; + cout << underscore << "라고 답변하였지.\n"; + return; + } + else{ + cout << underscore << "\"재귀함수가 뭔가요?\"\n"; + cout << underscore << "\"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.\n"; + cout << underscore << "마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.\n"; + cout << underscore << "그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어.\"\n"; + whatIsRecursion(recurNum-1, globRecurNum); + cout << underscore << "라고 답변하였지.\n"; + } +} + +int main(){ + int recursionNum = 0; + cin >> recursionNum; + + cout << "어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.\n"; + whatIsRecursion(recursionNum, recursionNum); +} \ No newline at end of file diff --git a/gaeun/03_recur_imple/2563_colour_papar.cpp b/gaeun/03_recur_imple/2563_colour_papar.cpp new file mode 100644 index 0000000..362bd58 --- /dev/null +++ b/gaeun/03_recur_imple/2563_colour_papar.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; + +int main(){ + int paperNum = 0; + int whitePaper[100][100] = {}; + int numOfOne = 0; + + cin >> paperNum; + + int *row_inputPaper = new int[paperNum]; + int *col_inputPaper = new int[paperNum]; + + for(int i=0; i> row_inputPaper[i] >> col_inputPaper[i]; + row_inputPaper[i] = row_inputPaper[i] - 1; + col_inputPaper[i] = col_inputPaper[i] - 1; + } + + for(int i=0; i= 100) break; + for(int col = col_inputPaper[i]; col < col_inputPaper[i]+10; col++){ + if(col >= 100) break; + whitePaper[row][col] = 1; + } + } + } + + for(int row = 0; row < 100; row++){ + for(int col = 0; col < 100; col++){ + if(whitePaper[row][col] == 1){ + numOfOne++; + } + } + } + + cout << numOfOne; + + delete []row_inputPaper; + delete []col_inputPaper; +} \ No newline at end of file diff --git a/gaeun/03_recur_imple/2941_croatia_alphabet.cpp b/gaeun/03_recur_imple/2941_croatia_alphabet.cpp new file mode 100644 index 0000000..2caf3c4 --- /dev/null +++ b/gaeun/03_recur_imple/2941_croatia_alphabet.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; + +int main(){ + int croatiaCounter = 0; + string input= ""; + + cin >> input; + for(int i=0; i +#include +#include +#include +using namespace std; + + +int main(){ + string input_gear1, input_gear2, input_gear3, input_gear4; + deque gear1dq, gear2dq, gear3dq, gear4dq; + vector> allGears = {gear1dq, gear2dq, gear3dq, gear4dq}; + + int idxGearTooth; + int numRotation; + int tmpWhichGear; + int tmpRotationDir; + queue whichGear; + queue rotationDir; + int score = 0; + + cin >> input_gear1; + cin >> input_gear2; + cin >> input_gear3; + cin >> input_gear4; + + cin >> numRotation; + + // get each rotation procedure and do processing + for(int i=0; i> tmpWhichGear >> tmpRotationDir; + whichGear.push(tmpWhichGear); + rotationDir.push(tmpRotationDir); + } + + // processing gear deque + for(int i=0; i<8; i++){ + gear1dq.push_back(input_gear1[i] - '0'); + gear2dq.push_back(input_gear2[i] - '0'); + gear3dq.push_back(input_gear3[i] - '0'); + gear4dq.push_back(input_gear4[i] - '0'); + } + + allGears = {gear1dq, gear2dq, gear3dq, gear4dq}; + for(int i=0; i +using namespace std; + + +bool field[51][51] = {0,}; +int fieldRow, fieldCol; + +bool dfs(int row, int col){ + // 범위 벗어나는 경우 종료 + if (row <= -1 || row >= fieldRow || col <= -1 || col >= fieldCol) return false; + + // 배추가 있는 노드에 대해 + if (field[row][col] == 1){ + // 1. 방문 처리 + field[row][col] = 0; + // 2. 해당 노드에 연결된 노드를 상하좌우 재귀로, 가장 깊은 노드까지 탐색 + dfs(row-1,col); + dfs(row,col-1); + dfs(row+1,col); + dfs(row,col+1); + return true; + } + // 배추가 없는 노드라면 + return false; +} + +int main(){ + int testCaseNum; + int cabageNum, cabageRow, cabageCol; + int wormNum = 0; + + // seperate input and output: DO NOT USE 'endl' + ios::sync_with_stdio(0); + cin.tie(0); + + // with regard to several testCase, + cin >> testCaseNum; + for(int test=0; test> fieldRow >> fieldCol >> cabageNum; + for(int i=0; i> cabageRow >> cabageCol; + field[cabageRow][cabageCol] = 1; + } + + // field debugging + /* + for(int i=0; i +#include +using namespace std; + +int maze[101][101] = {0,}; +int mazeRow, mazeCol; + +// 상,하,좌,우 이동 방향 +int dRow[] = {-1,1,0,0}; +int dCol[] = {0,0,-1,1}; + +int bfs(int r, int c){ + queue> q; + // 시작 node 삽입, 방문처리는 'maze[nRow][nCol] = maze[row][col] + 1' 로직으로 + q.push({r,c}); + while(!q.empty()){ // 더 이상 방문할 node가 없을 때까지 + int row = q.front().first; + int col = q.front().second; + q.pop(); // 시작 node 꺼내고, + /* + 방문하지 않은 인접 노드들 중 다음 조건을 만족시키는 노드만 큐에 삽입 + 1. maze 범위 벗어나지 않을 것 + 2. 갈 수 있는 길이며 첫 방문(1)일 것 + */ + // 상하좌우 + for(int i=0; i<4; i++){ + int nRow = row + dRow[i]; + int nCol = col + dCol[i]; + + // maze 범위 확인 + if(nRow <= -1 || nRow >= mazeRow || nCol <= -1 || nCol >= mazeCol) continue; + + // 갈 수 있는 길이고, 첫 방문이라면(1) 이전 노드 경로 길이에 +1, 큐에 삽입 + if(maze[nRow][nCol] == 1){ + maze[nRow][nCol] = maze[row][col] + 1; + q.push({nRow,nCol}); + } + } + // just for debugging + for(int i=0; i> mazeRow >> mazeCol; + for(int row=0; row +using namespace std; + +int picture[101][101]; +int col, row; +bool isVisitedR[101][101] = {0, }; +bool isVisitedG[101][101] = {0, }; +bool isVisitedB[101][101] = {0, }; + +bool isVisitedWeaknessB[101][101] = {0, }; +bool isVisitedWeaknessNotB[101][101] = {0, }; + +char dfsR(int r, int c){ + if(r < 0 || c <0 || r > row-1 || c > col-1) return '0'; + else{ + if(isVisitedR[r][c] == 0 && picture[r][c] == 'R'){ + isVisitedR[r][c] = 1; + dfsR(r-1,c); + dfsR(r+1,c); + dfsR(r,c-1); + dfsR(r,c+1); + return 'R'; + } + } + return '0'; +} +char dfsG(int r, int c){ + if(r < 0 || c <0 || r > row-1 || c > col-1) return '0'; + else{ + if(isVisitedG[r][c] == 0 && picture[r][c] == 'G'){ + isVisitedG[r][c] = 1; + dfsG(r-1,c); + dfsG(r+1,c); + dfsG(r,c-1); + dfsG(r,c+1); + return 'G'; + } + } + return '0'; +} +char dfsB(int r, int c){ + if(r < 0 || c <0 || r > row-1 || c > col-1) return '0'; + else{ + if(isVisitedG[r][c] == 0 && picture[r][c] == 'B'){ + isVisitedG[r][c] = 1; + dfsB(r-1,c); + dfsB(r+1,c); + dfsB(r,c-1); + dfsB(r,c+1); + return 'B'; + } + } + return '0'; +} +char dfsWeaknessB(int r, int c){ + if(r < 0 || c <0 || r > row-1 || c > col-1) return '0'; + else{ + if(isVisitedWeaknessB[r][c] == 0 && picture[r][c] == 'B'){ + isVisitedWeaknessB[r][c] = 1; + dfsWeaknessB(r-1,c); + dfsWeaknessB(r+1,c); + dfsWeaknessB(r,c-1); + dfsWeaknessB(r,c+1); + return 'B'; + } + } + return '0'; +} +char dfsWeaknessNotB(int r, int c){ + if(r < 0 || c <0 || r > row-1 || c > col-1) return '0'; + else{ + if(isVisitedWeaknessNotB[r][c] == 0 && picture[r][c] == 'C'){ + isVisitedWeaknessNotB[r][c] = 1; + dfsWeaknessNotB(r-1,c); + dfsWeaknessNotB(r+1,c); + dfsWeaknessNotB(r,c-1); + dfsWeaknessNotB(r,c+1); + return 'C'; + } + } + return '0'; +} + +int main(){ + // get the input + cin >> col; + row = col; + for(int i=0; i +#include +using namespace std; + +int main(){ + int childrenNum; + int groupNum; + int height; + int totalCost = 0; + + // get input + cin >> childrenNum >> groupNum; + + int* childHeight = new int[childrenNum]; + for(int i=0; i> childHeight[i]; + } + + // get cost of subsequent element + int* cost = new int[childrenNum - 1]; + for(int i=0; i childrenNum-2 - (groupNum - 1); i--){ + totalCost -= cost[i]; + } + + // print result + cout << totalCost; + +} \ No newline at end of file diff --git a/gaeun/06_hard_imple/1697_hide_n_seek.cpp b/gaeun/06_hard_imple/1697_hide_n_seek.cpp new file mode 100644 index 0000000..3602610 --- /dev/null +++ b/gaeun/06_hard_imple/1697_hide_n_seek.cpp @@ -0,0 +1,50 @@ +// 각 시점에서 3가지: +1, -1, *2. 최단경로 -> BFS + +#include +#include +using namespace std; + +int subin; +int sister; +int findTime[100001] = {0, }; + +void bfs(){ + queue q; + q.push(subin); // 시작 node 삽입 + + while(!q.empty()){ // 더 이상 방문할 node가 없을 때까지 + int currLoc = q.front(); + q.pop(); + + // 동생 찾았으면 결과 출력 + if(currLoc == sister){ + cout << findTime[currLoc]; + break; + } + + // 못찾았을 때, -1의 거리 이동 + if(currLoc-1 >= 0 && findTime[currLoc-1] == 0){ + findTime[currLoc - 1] = findTime[currLoc] + 1; // -1의 거리 이동에 findTime 1 증가 + q.push(currLoc - 1); + } + + // 못찾았을 때, +1의 거리 이동 + if(currLoc+1 <= 100000 && findTime[currLoc+1] == 0){ + findTime[currLoc + 1] = findTime[currLoc] + 1; + q.push(currLoc + 1); + } + + // 못찾았을 때, *2의 거리 이동 + if(currLoc*2 <= 100000 && findTime[currLoc*2] == 0){ + // 만약 currLoc = 0 이라면, continue 넣어주면ㄴ 좋겠지? 0에 아무리 곱해봐야 0인데.. + findTime[currLoc * 2] = findTime[currLoc] + 1; + q.push(currLoc * 2); + } + } +} + +int main(){ + + cin >> subin >> sister; + bfs(); +} \ No newline at end of file diff --git a/gaeun/06_hard_imple/2606_virus.cpp b/gaeun/06_hard_imple/2606_virus.cpp new file mode 100644 index 0000000..022e595 --- /dev/null +++ b/gaeun/06_hard_imple/2606_virus.cpp @@ -0,0 +1,48 @@ +// 감염되는 것 묶어내기 -> DFS +#include +#include +using namespace std; + +int computerNum; +int connectedPairNum; +vector computerMap[101]; +bool is_visited[101] = {0, }; +int result = 0; + +void dfs(int node); + +int main(){ + + // get input + cin >> computerNum; + cin >> connectedPairNum; + + // 인접리스트 구현 for DFS + for(int i=1; i<=connectedPairNum; i++){ + int a, b; + cin >> a >> b; + computerMap[a].push_back(b); + computerMap[b].push_back(a); + } + + // dfs + is_visited[1] = 1; + dfs(1); + + // print the result + cout << result; +} + +void dfs(int node){ + for(int i=0; i +#include +#include // to use sort() +using namespace std; + +int N; +int P[10] = {0,}; +vector> priceList; +int M; +string roomNumber = ""; + +int main(){ + // get inputs + cin >> N; + for(int i=0; i> P[i]; + priceList.push_back(make_pair(i, P[i])); + } + cin >> M; + + // sort price from the cheapest one - !!Lambda function!! + sort(priceList.begin(), priceList.end(), [](pair a, pair b){ + return a.second < b.second;} + ); + + // handling if '0' has the cheapest price + if(N==1){ + cout << 0; + return 0; + } + else if(priceList[0].first == 0){ + // 0만 살 수 있을 때 + if(M >= priceList[0].second && M < priceList[1].second){ + cout << 0; + return 0; + } + // 그렇지 않으면 맨 앞자리에 0 안됨 -> 일단 두번째로 싼 숫자 앉혀 + else if(M>=priceList[1].second){ + roomNumber = to_string(priceList[1].first); + M = M - priceList[1].second; + } + } + + // 이제 0이 아닌 숫자가 가장 싸거나, 0이 가장 앞자리에 오는 것이 보정된 상태 + // 1. make the longest number with the digit of cheapest price + while(M>=priceList[0].second){ + roomNumber += to_string(priceList[0].first); + M = M - priceList[0].second; + } + + // 2. 남는 돈으로 차액을 통해 큰 자리부터 바꿔나감 + // 만들어진 가장 긴 roonNumber의 모든 자리에 대해, + for(int i = 0; i < roomNumber.length(); i++){ + // 큰 수부터 해당 숫자까지 + for(int k = N-1; k > (roomNumber[i] - '0'); k--){ + // 차액이 남은 돈보다 작거나 같다면 + if(P[k] - P[(roomNumber[i] - '0')] <= M){ + // 차액만큼 M 감소시켜주고, roomNumber 바꿔 + M = M - (P[k] - P[(roomNumber[i] - '0')]); + roomNumber[i] = (k + '0'); + break; // 더 작은 수로 바꿀 필요 없으니 break + } + } + } + + cout << roomNumber; +} \ No newline at end of file diff --git a/gaeun/07/16234_population_movement.cpp b/gaeun/07/16234_population_movement.cpp new file mode 100644 index 0000000..5b45255 --- /dev/null +++ b/gaeun/07/16234_population_movement.cpp @@ -0,0 +1,94 @@ +#include +#include +#include +using namespace std; + +int A[50][50] = {0,}; +bool isVisited[50][50] = {0,}; +int N, L, R; +int drow[4] = {-1, 1, 0, 0}; // 상하좌우 +int dcol[4] = {0, 0, -1, 1}; // 상하좌우 +int countryNumInUnion = 0; +int populationSum = 0; +int newPopulation = 0; +int movementDays = 0; +vector> countryIdxInUnion; +bool isUnionFound = 1; + +void clearIsVisited() { + for (int r = 0; r < N; r++) { + for (int c = 0; c < N; c++) { + isVisited[r][c] = 0; + } + } +} + +// dfs: union발견 시 union 내 국가 수, 총 인구 수, node idx 저장 +void dfs(int row, int col) { + int nrow, ncol; + isVisited[row][col] = 1; + countryNumInUnion++; + populationSum += A[row][col]; + countryIdxInUnion.push_back({row, col}); + + for (int i = 0; i < 4; i++) { + nrow = row + drow[i]; + ncol = col + dcol[i]; + + if (nrow < 0 || nrow >= N || ncol < 0 || ncol >= N) continue; + + if (abs(A[row][col] - A[nrow][ncol]) >= L && abs(A[row][col] - A[nrow][ncol]) <= R) { + if (isVisited[nrow][ncol] == 0) { + dfs(nrow, ncol); + } + } + } +} + +int main() { + // get input + cin >> N >> L >> R; + for (int r = 0; r < N; r++) { + for (int c = 0; c < N; c++) { + cin >> A[r][c]; + } + } + + while (isUnionFound) { + // 한바퀴 다 돌면: isVisited, isUnionFound 초기화 + isUnionFound = 0; + clearIsVisited(); + + for (int r = 0; r < N; r++) { + for (int c = 0; c < N; c++) { + // 방문하지 않았던 노드라면, do dfs + if (!isVisited[r][c]) { + countryNumInUnion = 0; + populationSum = 0; + countryIdxInUnion.clear(); + dfs(r, c); + // union 발견 시, 인구 이동 + if (countryNumInUnion > 1) { + newPopulation = populationSum / countryNumInUnion; + for(int i=0; i +using namespace std; + +int N; +int M; +int K; +char GRID[11][11]; // 1x1 ~ NxM +string beLovedStrings[1000]; +int caseNum[1000]={0,}; +int dr[8] = {-1, 1, 0, 0, -1, 1, 1, -1}; // 상하좌우, 2, 3, 4, 1사분면 대각선 +int dc[8] = {0, 0, -1, 1, -1, -1, 1, 1}; // 상하좌우, 2, 3, 4, 1사분면 대각선 + +void dfs(int row, int col, int stringIdx, string beLovedStr, int charIdx, int strSize){ + int nrow, ncol; + + if(GRID[row][col] == beLovedStr[charIdx]){ + // 상하좌우, 각 대각선에 대해 + for(int i=0; i<8; i++){ + nrow = row + dr[i]; + ncol = col + dc[i]; + + // make it circular + if(nrow < 1) nrow = N; + if(nrow > N) nrow = 1; + if(ncol < 1) ncol = M; + if(ncol > M) ncol = 1; + + // 특정 방향에 대해 주어진 문자열의 '다음 글자'와 일치하는지 확인. 일치한다면, + int checkIdx = charIdx + 1; + if(GRID[nrow][ncol] == beLovedStr[checkIdx]){ + // 주어진 문자열의 끝까지 검사했다면 경우의 수 +1 + if(checkIdx == strSize-1){ + caseNum[stringIdx]++; + continue; // 다른 방향에서 만족시키는 경우 있는지 확인하러. + } + // 아직 아니라면 특정 방향에 대해 그 다음 글자 일치 여부 확인하기 위한 dfs 실행. + else dfs(nrow, ncol, stringIdx, beLovedStr, checkIdx, strSize); + } + } + } + +} + +int main(){ + // get input + cin >> N >> M >> K; + for(int i=1; i<=N; i++){ + for(int j=1; j<=M; j++){ + cin >> GRID[i][j]; + } + } + for(int i=0; i> beLovedStrings[i]; + } + + // use greedy to find the number of cases + for(int stringIdx=0; stringIdx 최대 10*10*8^5*1000 (+ alpha) = 4억 = 4초 +// grid에서 만들 수 있는 문자열을 모두 저장 후, 문자열을 k개 입력받아 search -> 최대 10*10*8^5(3백만대) + 탐색 +// O(logN)을 갖고, key-value쌍을 지원하는 map을 써봅시다. + +#include +#include +using namespace std; + +int N; +int M; +int K; +char GRID[11][11]; // 1x1 ~ NxM +map strCases; // doesn't allow duplicated strings +int dr[8] = {-1, 1, 0, 0, -1, 1, 1, -1}; // 상하좌우, 2, 3, 4, 1사분면 대각선 +int dc[8] = {0, 0, -1, 1, -1, -1, 1, 1}; // 상하좌우, 2, 3, 4, 1사분면 대각선 + +void dfs(int row, int col, string str, int charNum){ + int nrow, ncol; + + str += GRID[row][col]; + charNum++; + + // map에 저장되어 있지 않는 문자열이라면 저장 + if(strCases.find(str) == strCases.end()){ + strCases.insert({str,1}); + } + // 이미 저장된 것이라면 경우의 수만 증가 + else{ + strCases[str]++; + } + + // 글자수가 5 미만이라면 계속 탐색 + if(charNum < 5){ + // 상하좌우, 각 대각선에 대해 + for(int i=0; i<8; i++){ + nrow = row + dr[i]; + ncol = col + dc[i]; + + // make it circular + if(nrow < 1) nrow = N; + if(nrow > N) nrow = 1; + if(ncol < 1) ncol = M; + if(ncol > M) ncol = 1; + + // dfs + dfs(nrow, ncol, str, charNum); + } + } + + +} + +int main(){ + // print after get all the inputs + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + // get input + cin >> N >> M >> K; + for(int i=1; i<=N; i++){ + for(int j=1; j<=M; j++){ + cin >> GRID[i][j]; + } + } + + // store all possible strings + for(int i=1; i<=N; i++){ + for(int j=1; j<=M; j++){ + dfs(i,j,"",0); + } + } + + for(int i=0; i> beLovedString; + + // GRID에서 만들어질 수 없는 문자열이라면 0 출력 + if(strCases.find(beLovedString) == strCases.end()){ + cout << 0 << '\n'; + } + // 만들어질 수 있는 문자열이라면 그 경우의 수 출력 + else cout << strCases[beLovedString] << '\n'; + } +} \ No newline at end of file diff --git a/gaeun/08/5212_global_warming.cpp b/gaeun/08/5212_global_warming.cpp new file mode 100644 index 0000000..98e4fb4 --- /dev/null +++ b/gaeun/08/5212_global_warming.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +using namespace std; + +int R; +int C; +char** MAP; // Q. 동적할당 필요한 것 아닌가? +int dr[4] = {-1, 1, 0, 0}; // in the order of 상하좌우 +int dc[4] = {0, 0, -1, 1}; // in the order of 상하좌우 +vector> disappearIdx; +vector> landIdx; + +int main(){ + // get R and C + cin >> R >> C; + + // dynamic allocation for 2D array + MAP = new char*[R]; + for(int i=0; i> MAP[i][j]; + } + } + + // find the lands will be disappeared + for(int i=0; i=R || j+dc[k]<0 || j+dc[k]>=C){ // 범위 초과는 바다로 간주 + cnt++; + continue; + } + if(MAP[i+dr[k]][j+dc[k]] == '.'){ // 상하좌우에 대해 바다가 3면 이상인지 확인 + cnt++; + } + } + if(cnt < 3){ // 3면 미만의 살아남을 땅이라면, + landIdx.push_back(make_pair(i,j)); // 해당 땅의 idx를 pair로 저장 + } + else{ // 사라질 땅 idx 저장 + disappearIdx.push_back(make_pair(i,j)); + } + } + } + } + + // 사라질 땅을 바다로 교체 + for(auto x:disappearIdx){ + MAP[x.first][x.second] = '.'; + } + + // find the smallest and the largest row index + sort(landIdx.begin(), landIdx.end(), [](pair r1, pair r2){ + return r1.first < r2.first; + }); + int smallestRow = landIdx[0].first; + int largestRow = landIdx[landIdx.size()-1].first; + + // find the smallest and the largest column index + sort(landIdx.begin(), landIdx.end(), [](pair r1, pair r2){ + return r1.second < r2.second; + }); + int smallestCol = landIdx[0].second; + int largestCol = landIdx[landIdx.size()-1].second; + + // print the new map + for(int i=smallestRow; i<=largestRow; i++){ + for(int j=smallestCol; j<=largestCol; j++){ + cout << MAP[i][j]; + } + cout << endl; + } +} \ No newline at end of file diff --git a/gaeun/09/1525_bfs.cpp b/gaeun/09/1525_bfs.cpp new file mode 100644 index 0000000..981c2e5 --- /dev/null +++ b/gaeun/09/1525_bfs.cpp @@ -0,0 +1,58 @@ +// 최단 경로를 찾는 문제로 생각 가능. -> bfs + +#include +#include +#include +#include // to use swap() +using namespace std; + +string answer = "123456780"; +string str; +queue> q; +set isVisited; +int dr[4]={-1,1,0,0}; // 상하좌우 +int dc[4]={0,0,-1,1}; // 상하좌우 + +int bfs(){ + q.push(make_pair(str, 0)); + isVisited.insert(str); + + while(!q.empty()){ + string currStr = q.front().first; + int cnt = q.front().second; + q.pop(); + + // 정답과 일치 시 + if(currStr == answer) return cnt; + + // 정답과 일치 x + // 1. 0 위치 찾아 2차원 좌표로 맵핑 + int idx0 = currStr.find('0'); + int r = idx0 / 3; + int c = idx0 % 3; + + // 2. 상하좌우에 대해 + for(int i=0; i<4; i++){ + int nr = r + dr[i]; + int nc = c + dc[i]; + if(nr < 0 || nr > 2 || nc < 0 || nc > 2 ) continue; + string nextStr = currStr; + swap(nextStr[r*3+c], nextStr[nr*3+nc]); + if(isVisited.find(nextStr) == isVisited.end()){ + isVisited.insert(nextStr); + q.push(make_pair(nextStr, cnt++)); + } + } + + } + return -1; +} + +int main(){ + for(int i=0; i<9; i++){ + char c; + cin >> c; + str += c; + } + cout << bfs(); +} \ No newline at end of file diff --git a/gaeun/09/1525_puzzle.cpp b/gaeun/09/1525_puzzle.cpp new file mode 100644 index 0000000..1df39fd --- /dev/null +++ b/gaeun/09/1525_puzzle.cpp @@ -0,0 +1,169 @@ +// cnt 1번 증가에 최대 (9+9)*9*4*(9+9) -> cnt가 8000 이상이 되면 time over +// Q. 시간복잡도 이렇게 계산하는 것 맞나? +// bfs는 one of 완탐, bfs도 시간초과 안되는데 greedy로 시간초과? -> 무한 loop 걸린겨 + +#include +using namespace std; + +int sorted[3][3] = {{1,2,3},{4,5,6},{7,8,0}}; +int puzzle[3][3]; +int dr[4]={-1,1,0,0}; // 상하좌우 +int dc[4]={0,0,-1,1}; // 상하좌우 +int cnt = 0; + +bool checkSolved(){ + for(int i=0; i<3; i++){ + for(int j=0; j<3; j++){ + if(puzzle[i][j] != sorted[i][j]){ + return false; + } + } + } + return true; +} + +int main(){ + // get input + for(int i=0; i<3; i++){ + for(int j=0; j<3; j++){ + cin >> puzzle[i][j]; + } + } + + while(!checkSolved()){ + // check if it's sorted + if(checkSolved()){ + cout << cnt; + return 0; + } + + // 정렬되지 않은 채 0이 마지막 위치에 도달했다면 -1 출력. + if(!checkSolved() && puzzle[2][2] == 0){ + cout << -1; + return 0; + } + + // 정렬 + for(int i=0; i<3; i++){ + for(int j=0; j<3; j++){ + if(puzzle[i][j] == 0){ + int minDiff = 10; + int swapRow; + int swapCol; + + // 1.search: 현재 0 위치에 와야하는 값과 차가 가장 작은 상하좌우 원소 찾기 + for(int d=0; d<4; d++){ + int nr = i+dr[d]; + int nc = j+dc[d]; + // 범위 넘어가면 제외 + if(nr < 0 || nr > 2 || nc < 0 || nc > 2 ) continue; + if(abs(sorted[i][j] - puzzle[nr][nc]) < minDiff){ + minDiff = abs(sorted[i][j] - puzzle[nr][nc]); + swapRow = nr; + swapCol = nc; + } + } + + // 2.swap + cnt++; + puzzle[i][j] = puzzle[swapRow][swapCol]; + puzzle[swapRow][swapCol] = 0; + + // 3. check if it's sorted + if(checkSolved()){ + cout << cnt; + return 0; + } + + // 4. 정렬되지 않은 채 0이 마지막 위치에 도달했다면 -1 출력. + if(!checkSolved() && puzzle[2][2] == 0){ + cout << -1; + return 0; + } + } + } + } + } +} + +// #include +// using namespace std; + +// int sorted[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}}; +// int puzzle[3][3]; +// int dr[4] = {-1, 1, 0, 0}; // 상하좌우 +// int dc[4] = {0, 0, -1, 1}; // 상하좌우 +// int cnt = 0; + +// bool checkSolved() { +// for (int i = 0; i < 3; i++) { +// for (int j = 0; j < 3; j++) { +// if (puzzle[i][j] != sorted[i][j]) { +// return false; +// } +// } +// } +// return true; +// } + +// int main() { +// // get input +// for (int i = 0; i < 3; i++) { +// for (int j = 0; j < 3; j++) { +// cin >> puzzle[i][j]; +// } +// } + +// while (!checkSolved()) { + +// // the last element became 0 w/o sorted +// if (puzzle[2][2] == 0 && !checkSolved()) { +// cout << -1; +// return 0; +// } + +// // 0의 위치 찾기 +// int zeroRow, zeroCol; +// for (int i = 0; i < 3; i++) { +// for (int j = 0; j < 3; j++) { +// if (puzzle[i][j] == 0) { +// zeroRow = i; +// zeroCol = j; +// break; +// } +// } +// } + +// // 0의 새로운 위치 업데이트 및 swap +// int minDiff = 10; +// int swapRow = zeroRow; +// int swapCol = zeroCol; + +// // 1. search: 현재 0 위치에 와야하는 값과 차가 가장 작은 상하좌우 원소 찾기 +// for (int d = 0; d < 4; d++) { +// int nr = zeroRow + dr[d]; +// int nc = zeroCol + dc[d]; +// // 범위 넘어가면 제외 +// if (nr < 0 || nr > 2 || nc < 0 || nc > 2) continue; +// // swap 대상 찾기 +// if (abs(sorted[zeroRow][zeroCol] - puzzle[nr][nc]) < minDiff) { +// minDiff = abs(sorted[zeroRow][zeroCol] - puzzle[nr][nc]); +// swapRow = nr; +// swapCol = nc; +// } +// } + +// // 2. swap +// cnt++; +// puzzle[zeroRow][zeroCol] = puzzle[swapRow][swapCol]; +// puzzle[swapRow][swapCol] = 0; + +// // 3. check if it's sorted +// if (checkSolved()) { +// cout << cnt; +// return 0; +// } +// } + +// cout << cnt; +// } diff --git a/gaeun/09/19583_cyber_semester_opening_string_handling.cpp b/gaeun/09/19583_cyber_semester_opening_string_handling.cpp new file mode 100644 index 0000000..fac7acb --- /dev/null +++ b/gaeun/09/19583_cyber_semester_opening_string_handling.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +using namespace std; + +string S,E,Q; +set startMem; +set endMem; +int attendanceCnt = 0; + + +int rmColonNtoInt(string str){ + str.erase(remove(str.begin(), str.end(), ':'), str.end()); + // remove(): 삭제되어야 할 원소들의 위치에 유지될 원소들의 값을 덮어 씌움 -> 뒷쪽에 쓸데없는 데이터가 남음 + // erase() 함께 사용: remove() 사용 이후 발생하는 필요없는 중복 데이터 삭제 가능. + return stoi(str); +} + +int main(){ + ios::sync_with_stdio(0); + cin.tie(0); + + cin >> S >> E >> Q; + int s,e,q; + s = rmColonNtoInt(S); + e = rmColonNtoInt(E); + q = rmColonNtoInt(Q); + + string time; + string memberName; + while(cin >> time >> memberName){ + int recordedTime = rmColonNtoInt(time); + // 시작 또는 시작한 시간에 참가했던 멤버라면, + if(recordedTime <= s){ + startMem.insert(memberName); + } + if(recordedTime >= e && recordedTime <= q){ + endMem.insert(memberName); + } + } + + for(auto name : startMem){ + // 두 이름이 startMem, endMem에 모두 존재하면, + if(find(endMem.begin(), endMem.end(), name) != endMem.end()){ + attendanceCnt++; + } + } + cout << attendanceCnt; + +} \ No newline at end of file diff --git a/gaeun/09/19583_sol.cpp b/gaeun/09/19583_sol.cpp new file mode 100644 index 0000000..7714a10 --- /dev/null +++ b/gaeun/09/19583_sol.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +string S,E,Q; +map member; +int attendanceCnt = 0; + +int main(){ + ios::sync_with_stdio(0); + cin.tie(0); + + cin >> S >> E >> Q; + + string time; + string memberName; + + // 입력 최대 10만개 + while(cin >> time >> memberName){ // EOF(ctrl+z같은) 받으면 종료 + // 시작 또는 시작한 시간에 참가했던 멤버 기록 + if(time <= S){ + member.insert({memberName,0}); + } + // 시작할 때 있었고, 끝까지 참여한 멤버라면 출석 인원 증가 + if(time >= E && time <= Q){ + if((member.find(memberName) != member.end()) && member[memberName] == 0){ + attendanceCnt++; + member[memberName]++; // to 중복방지 + } + } + } + cout << attendanceCnt; + +} \ No newline at end of file diff --git a/gaeun/09/19583_timeover.cpp b/gaeun/09/19583_timeover.cpp new file mode 100644 index 0000000..982000a --- /dev/null +++ b/gaeun/09/19583_timeover.cpp @@ -0,0 +1,43 @@ +// Q. 시간 초과가 발생하는 이유는? + +#include +#include +#include +using namespace std; + +string S,E,Q; +unordered_set startMem; // 중복 배제를 위한 set 사용. find는 O(log(n)) +unordered_set endMem; +int attendanceCnt = 0; + +int main(){ + ios::sync_with_stdio(0); + cin.tie(0); + + cin >> S >> E >> Q; + + string time; + string memberName; + + // 입력 최대 10만개 + while(cin >> time >> memberName){ // EOF(ctrl+z같은) 받으면 종료 + // 시작 또는 시작한 시간에 참가했던 멤버 기록 + if(time <= S){ + startMem.insert(memberName); // log(n) + } + // 끝날때까지 있던 멤버 기록 + if(time >= E && time <= Q){ + endMem.insert(memberName); + } + } + + // 10만개*(20(string 최대 길이) * log(100,000) = 16.6) = 166만 + for(auto name : startMem){ + // 두 조건 모두 만족하면 출석한 인원으로 카운트. + if(find(endMem.begin(), endMem.end(), name) != endMem.end()){ + attendanceCnt++; + } + } + cout << attendanceCnt; + +} \ No newline at end of file diff --git a/gaeun/10/1715_card_sorting.cpp b/gaeun/10/1715_card_sorting.cpp new file mode 100644 index 0000000..3ff837f --- /dev/null +++ b/gaeun/10/1715_card_sorting.cpp @@ -0,0 +1,31 @@ +// 최소 합 구하기 +// 입력이 최대 10만개 -> 완탐은 안될듯. + +#include +#include // to use priority_queue +#include +using namespace std; + +int cardNum; +priority_queue, greater> pq; // ascending +int minSortingNum = 0; + +int main(){ + cin >> cardNum; + for(int i=0; i> numInDummy; + pq.push(numInDummy); + } + while (pq.size() > 1) { + int card1 = pq.top(); + pq.pop(); + int card2 = pq.top(); + pq.pop(); + int nextCard = card1 + card2; + pq.push(nextCard); + minSortingNum+=nextCard; + } + cout << minSortingNum; + +} \ No newline at end of file diff --git a/gaeun/10/5427_fire.cpp b/gaeun/10/5427_fire.cpp new file mode 100644 index 0000000..a2427e2 --- /dev/null +++ b/gaeun/10/5427_fire.cpp @@ -0,0 +1,108 @@ +#include +#include +using namespace std; + +int testCaseNum; +int w,h; +char buildingMap[1000][1000]; +queue> sangeun; +queue> fire; +int dr[4] = {-1, 1, 0, 0}; // 상하좌우 +int dc[4] = {0, 0, -1, 1}; // 상하좌우 + +void fireSpreading(){ + // 현재 모든 불 위치에 대해 + int fireQsize = fire.size(); + for(int fireIdx=0; fireIdx < fireQsize; fireIdx++){ + pair currFire = fire.front(); + int r = currFire.first; + int c = currFire.second; + fire.pop(); + + // spreading + for(int i=0; i<4; i++){ + int nr = r + dr[i]; + int nc = c + dc[i]; + + if(nr >= h || nr < 0 || nc >= w || nc < 0) continue; + if(buildingMap[nr][nc] != '.') continue; + + buildingMap[nr][nc] = '*'; + fire.push(make_pair(nr,nc)); + } + } +} + +int moveSangeun(){ + int escapeTime = 0; + + // 상근이의 위치를 담은 queue가 비지 않았다면, + while(!sangeun.empty()){ + // 1. 탈출 시간 증가 + escapeTime++; + + // 2. 불 번지게 만든 후 + fireSpreading(); + + // 3. 상근이의 위치 탐색 + int sangeunQsize = sangeun.size(); + for(int sangeunIdx = 0; sangeunIdx < sangeunQsize; sangeunIdx++){ + pair currSangeun = sangeun.front(); + int r = currSangeun.first; + int c = currSangeun.second; + sangeun.pop(); + + for(int i=0; i<4; i++){ + int nr = r + dr[i]; + int nc = c + dc[i]; + + // 범위를 벗어나면 탈출한 것 + if(nr >= h || nr < 0 || nc >= w || nc < 0) return escapeTime; // escape + // '#'벽이나, '*'불로는 움직일 수 없음 + if(buildingMap[nr][nc] != '.') continue; + + buildingMap[nr][nc] = '@'; + sangeun.push({nr,nc}); + } + } + } + + // 더 이상 '.'이 존재하지 않으면 sanguen queue는 빌 것이고, 이는 탈출하지 못함을 의미. + return -1; +} + +int main(){ + ios::sync_with_stdio(0); + cin.tie(0); + + cin >> testCaseNum; + for(int i=0; i> w >> h; + for(int r=0; r> buildingMap[r][c]; + + // track the location of sangeun + if(buildingMap[r][c] == '@'){ + sangeun.push(make_pair(r,c)); + } + // track the location of fire + if(buildingMap[r][c] == '*'){ + fire.push(make_pair(r,c)); + } + } + } + + // get the result + int escapeTime = moveSangeun(); + + // print the result + if(escapeTime != -1) cout << escapeTime << '\n'; + else cout << "IMPOSSIBLE" << '\n'; + + // reset + while (!sangeun.empty()) sangeun.pop(); + while (!fire.empty()) fire.pop(); + } +} \ No newline at end of file diff --git a/gaeun/11/1052_bit_shift.cpp b/gaeun/11/1052_bit_shift.cpp new file mode 100644 index 0000000..005a87f --- /dev/null +++ b/gaeun/11/1052_bit_shift.cpp @@ -0,0 +1,26 @@ +// fav sol: bit shift +#include + +#define BITS 32 + +int count(int num){ + int cnt = 0; + for(int i=0; i K){ + N++; + purchasedBottle++; + } + + printf("%d", purchasedBottle); +} \ No newline at end of file diff --git a/gaeun/11/1052_bottle.cpp b/gaeun/11/1052_bottle.cpp new file mode 100644 index 0000000..f9f8e35 --- /dev/null +++ b/gaeun/11/1052_bottle.cpp @@ -0,0 +1,46 @@ +// 1. N을 2진수로 표현한다. +// 2. 2진수로 표현된 N의 bit 수를 센다. 이 때, K = bit 수 +// 3. K 이하의 비트수가 되도록 1을 더해나간다. 더해진 1의 수가 구매한 물병 수. + +#include +using namespace std; + +int N, K; +int bottlePurchased = 0; + +string toBinary(int n){ + string bin = ""; + + if(n == 0) bin = "0"; + while(n > 0){ + bin = ((n % 2 == 0) ? '0' : '1') + bin; + n = n/2; + } + return bin; +} + +int main(){ + cin >> N >> K; + + // express N in binary + string bin = toBinary(N); + + // count the number of 1 + int numOfone = 0; + for(int i=0; i K){ + N++; + bottlePurchased++; + + string bin = toBinary(N); + numOfone = 0; + for(int i=0; i +#include +using namespace std; + +int main(){ + int N, K; + cin >> N >> K; + + int purchasedBottle = 0; + + // bitset: 1인 bit을 설정한다 -> .count method는 설정된 bit를, 즉 1인 bit를 셈. + while(bitset<32>(N).count() > K){ + N++; + purchasedBottle++; + } + + cout << purchasedBottle; +} \ No newline at end of file diff --git a/gaeun/11/12764_cyzibang.cpp b/gaeun/11/12764_cyzibang.cpp new file mode 100644 index 0000000..82f8372 --- /dev/null +++ b/gaeun/11/12764_cyzibang.cpp @@ -0,0 +1,90 @@ +// for문을 쓰니 아니나다를까 시간초과 + +#include +#include +using namespace std; + +// pair의 first 기준 min heap(작을수록 top에) +struct ascendingFirst{ + bool operator()(const pair& a, const pair& b){ + return a.first > b.first; + } +}; + +// pair의 second 기준 min heap(작을수록 top에) +struct ascendingSecond{ + bool operator()(const pair& a, const pair& b){ + return a.second > b.second; + } +}; + +int N; +priority_queue, vector>, ascendingFirst> startPQ; +priority_queue, vector>, ascendingSecond> endPQ; +vector seat(100000, 0); +int maxIdx = 0; +map, int> seatMap; +vector seatStatus(100000, true); +int emptySeatIdx; + +void findEmptySeat(){ + // get the smallest number of empty seat + for(int i=0; i<100000; i++){ + if(seatStatus[i] == true){ + emptySeatIdx = i; + break; + } + } + + // update the max num of seat + if(emptySeatIdx > maxIdx) maxIdx = emptySeatIdx; +} + +int main(){ + cin >> N; + for(int i=0; i> P >> Q; + startPQ.push({P,Q}); + endPQ.push({P,Q}); + } + + while(!startPQ.empty()){ + if(startPQ.top().first < endPQ.top().second){ + // 1. '<20,50>, 0'과 같이 특정시간 이용자가 앉는 자리 저장 + findEmptySeat(); + seatMap[startPQ.top()] = emptySeatIdx; // map 요소 추가: 1. insert(), 2. [] 연산자 + + // 2. 해당 자리에 앉았던 사람 명 수 기억, 해당 자리 occupied 처리 + seat[emptySeatIdx]++; + seatStatus[emptySeatIdx] = false; + + // 3. 변수 업데이트 + startPQ.pop(); + } + else{ + // 1. 사용기간 끝난 자리 release + while(startPQ.top().first > endPQ.top().second){ + seatStatus[seatMap[endPQ.top()]] = true; + endPQ.pop(); + } + + // 2. 최소 번호의 자리에 앉히기, 인원 증가, occupied 처리 + findEmptySeat(); + seat[emptySeatIdx]++; + seatStatus[emptySeatIdx] = false; + + // 4. 앉을 자리 저장 + seatMap[startPQ.top()] = emptySeatIdx; + + // 5. 변수 update + startPQ.pop(); + } + } + + cout << maxIdx + 1 << endl; + for(int i=0; i +#include +using namespace std; + +// pair의 first 기준 min heap(작을수록 top에) +struct ascendingFirst{ + bool operator()(const pair& a, const pair& b){ + return a.first > b.first; + } +}; + +// pair의 second 기준 min heap(작을수록 top에) +struct ascendingSecond{ + bool operator()(const pair& a, const pair& b){ + return a.second > b.second; + } +}; + +int N; +priority_queue, vector>, ascendingFirst> startPQ; +priority_queue, vector>, ascendingSecond> endPQ; +priority_queue, greater> emptySeatPQ; // min-heap +vector seat(100000, 0); +int maxIdx = 1; +map, int> seatMap; +int emptySeatIdx; + +void findEmptySeat(){ + if(emptySeatPQ.empty()){ + emptySeatPQ.push(maxIdx); + maxIdx++; + } + // get the smallest number of empty seat + emptySeatIdx = emptySeatPQ.top(); + emptySeatPQ.pop(); +} + +int main(){ + cin >> N; + for(int i=0; i> P >> Q; + startPQ.push({P,Q}); + endPQ.push({P,Q}); + } + + while(!startPQ.empty()){ + if(startPQ.top().first < endPQ.top().second){ + // 1. '<20,50>, 0'과 같이 특정시간 이용자가 앉는 자리 저장 + findEmptySeat(); + seatMap[startPQ.top()] = emptySeatIdx; // map 요소 추가: 1. insert(), 2. [] 연산자 + + // 2. 해당 자리에 앉았던 사람 명 수 기억 + seat[emptySeatIdx]++; + + // 3. 변수 업데이트 + startPQ.pop(); + } + else{ + // 1. 사용기간 끝난 자리 release + while(startPQ.top().first > endPQ.top().second){ + emptySeatPQ.push(seatMap[endPQ.top()]); + endPQ.pop(); + } + + // 2. 최소 번호의 자리에 앉히기, 인원 증가, occupied 처리 + findEmptySeat(); + seat[emptySeatIdx]++; + + // 4. 앉을 자리 저장 + seatMap[startPQ.top()] = emptySeatIdx; + + // 5. 변수 update + startPQ.pop(); + } + } + + cout << maxIdx-1 << endl; + for(int i=1; i +#include +using namespace std; + +int N; +vector> userVec; +priority_queue, vector>, greater>> seatAllocPQ; +priority_queue, greater> emptySeatPQ; // min-heap +vector seat(100000, 0); +int maxIdx=0; + +int main(){ + // get input + cin >> N; + int P, Q; + for(int i=0; i> P >> Q; + userVec.push_back({P,Q}); + } + + // 시작시간 기준 오름차순 정렬 + sort(userVec.begin(), userVec.end()); + + for(int i=0; i seatAllocPQ.top().first){ + emptySeatPQ.push(seatAllocPQ.top().second); + seatAllocPQ.pop(); + } + else break; + } + + // 새로운 자리 할당 + if(emptySeatPQ.empty()){ + seatAllocPQ.push({userVec[i].second, maxIdx}); + seat[maxIdx]++; + maxIdx++; + } + + // 빈자리가 났다면, 그 중 가장 작은 번호의 자리 할당 + else{ + int seatIdx = emptySeatPQ.top(); + seatAllocPQ.push({userVec[i].second, seatIdx}); + seat[seatIdx]++; + emptySeatPQ.pop(); + } + } + + cout << maxIdx << endl; + for(int i=0; i +#include +#include +#include +#include + +using namespace std; + +int solution(int coin, vector cards) { + int answer = 1; + + // 1. find n and set the target sum + int n = cards.size(); + + // 2. make a card deck + set deck; + for (int i=0; i newCards; + while(ptr < n){ + // init flag + bool isFound = false; + + // add two new cards every iteration + newCards.insert(cards[ptr]); + newCards.insert(cards[ptr+1]); + ptr += 2; + + // if a pair can be made within the deck + for(int element: deck){ + int target = (n+1) - element; + if((deck.find(target) != deck.end())){ + deck.erase(element); + deck.erase(target); + isFound = true; + answer++; + break; + } + } + + // one from the deck, the other from the new cards + if(!isFound && coin >= 1){ + for(int element: deck){ + int target = (n+1) - element; + if((newCards.find(target) != newCards.end())){ + deck.erase(element); + newCards.erase(target); + coin--; + isFound = true; + answer++; + break; + } + } + } + + // two from the new cards + if(!isFound && coin >= 2){ + for(int element: newCards){ + int target = (n+1) - element; + if((newCards.find(target) != newCards.end())){ + newCards.erase(element); + newCards.erase(target); + coin -= 2; + isFound = true; + answer++; + break; + } + } + } + if(!isFound) break; + } + + return answer; +} + + +int main() { + int coin = 2; + vector vec = {5, 8, 1, 2, 9, 4, 12, 11, 3, 10, 6, 7}; + cout << solution(coin, vec); + + return 0; +} \ No newline at end of file diff --git a/gaeun/12/sol.cpp b/gaeun/12/sol.cpp new file mode 100644 index 0000000..beefe29 --- /dev/null +++ b/gaeun/12/sol.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include + +using namespace std; + +int solution(int coin, vector cards) { + int answer = 1; + + // 1. find n and set the target sum + int n = cards.size(); + + // 2. make a card deck + set deck; + for (int i=0; i newCards; + while(ptr < n){ + // init flag + bool isFound = false; + + // add two new cards every iteration + newCards.insert(cards[ptr]); + newCards.insert(cards[ptr+1]); + ptr += 2; + + // if a pair can be made within the deck + for(int element: deck){ + int target = (n+1) - element; + if((deck.find(target) != deck.end())){ + deck.erase(element); + deck.erase(target); + isFound = true; + answer++; + break; + } + } + + // one from the deck, the other from the new cards + if(!isFound && coin >= 1){ + for(int element: deck){ + int target = (n+1) - element; + if((newCards.find(target) != newCards.end())){ + deck.erase(element); + newCards.erase(target); + coin--; + isFound = true; + answer++; + break; + } + } + } + + // two from the new cards + if(!isFound && coin >= 2){ + for(int element: newCards){ + int target = (n+1) - element; + if((newCards.find(target) != newCards.end())){ + newCards.erase(element); + newCards.erase(target); + coin -= 2; + isFound = true; + answer++; + break; + } + } + } + if(!isFound) break; + } + + return answer; +} \ No newline at end of file diff --git a/gaeun/13/17825_yutnori.cpp b/gaeun/13/17825_yutnori.cpp new file mode 100644 index 0000000..61c954e --- /dev/null +++ b/gaeun/13/17825_yutnori.cpp @@ -0,0 +1,21 @@ +#include +#include + +using namespace std; + +int dice[10]; // 주사위에서 나올 수 10개 +int horse[4]; // 말 4개 +int map[33]; // 윷놀이 판에 존재하는 33개의 node(시작, 도착 포함) +bool isHorse[33]; // 각 node에 horse 존재 여부 +int score[33]; // 각 node의 점수 + +void initMap(); +void dfs(); + +int main(){ + +} + +void initMap(){ + +} \ No newline at end of file diff --git a/gaeun/13/2110_router.cpp b/gaeun/13/2110_router.cpp new file mode 100644 index 0000000..04ba875 --- /dev/null +++ b/gaeun/13/2110_router.cpp @@ -0,0 +1,72 @@ +#include +#include +#include // sort() +using namespace std; + +int C,N; +vector X; + +int findMinDist(); + +int main(){ + // get the number of house and router + cin >> N >> C; + + // get each coordinate of routers + for(int i=0; i> coordinate; + X.push_back(coordinate); + } + + // sort in ascending order + sort(X.begin(), X.end()); + + // find the minimum distance between routers + cout << findMinDist(); +} + +int findMinDist(){ + // goal: find maximum gap satisfies the given conditions + int gap = 0; + int start = 1; // smallest possible gap + int end = X.back() - X.front(); // biggest possible gap + + // binary search의 조건을 만족시키는 동안, + while(start <= end){ + // 첫번째 공유기에는 무조건 설치 + int installedhouse = X[0]; + int cnt = 1; + + // 왼쪽부터 순차적으로 설치, 특정 거리보다 큰 gap을 가져야 설치. 이 때, '특정 거리'는 bianry search를 활용하고자 mid를 이용. + int mid = (start + end)/2; // 초기 mid값은 주어진 공유기들의 최대 gap의 절반으로. + for(int i=1; i= mid){ + // 공유기를 설치했다면, 기준점을 업데이트하여 다음 설치할 집을 찾도록 + installedhouse = X[i]; + + // 공유기 설치 개수 증가 + cnt++; + } + } + + // 주어진 공유기 수보다 같거나 많이 설치했다면 -> start를 키워 기준 거리(mid) 늘려서 재탐색 + if(cnt >= C){ + start = mid+1; + gap = mid; // 조건을 만족시켰으므로 gap update. + } + + // 적게 설치했다면 -> end를 감소시켜 기준 거리(mid) 줄여서 재탐색 + else{ + end = mid-1; + } + } + return gap; +} + + +// ** Binary Search: +// 정렬되어 있는 리스트에서, 탐색 범위를 절반씩 좁혀가며 데이터를 탐색하는 방법. +// start, mid, end의 세 변수를 이용하며, 데이터를 mid와 비교하며 세 변수를 업데이트. +// O(logN) 보장 \ No newline at end of file diff --git a/gaeun/13/2352_semiconductor_design.cpp b/gaeun/13/2352_semiconductor_design.cpp new file mode 100644 index 0000000..0fbdf5f --- /dev/null +++ b/gaeun/13/2352_semiconductor_design.cpp @@ -0,0 +1,41 @@ +// O(N^2)이면 TLE.. +// 질문) 이분탐색으로 LIS를 구하면, 길이는 맞으나 그 안에 담겨있는 원소가 다를 수 있다. + +#include +#include +#include + +using namespace std; + +int portNum; +vector connection; +vector findSeq; + +int main(){ + // get the number of port + cin >> portNum; + + // get the connections + for(int i=0; i> num; + connection.push_back(num); + } + + // 이분탐색을 활용한 최장 증가 수열 길이 찾기 + for(int i=0; i +#include + +using namespace std; + +int dist; +stack acc; + +void sol(int N, int K){ + //cin >> N >> K; + dist = N - 1; + acc.push(K); + dist = dist - K; + + while(dist!=0){ + int currAcc = acc.top(); + int caseK=0; + int checkAcc=0; + bool accFlag = false; + + // check if accel is available + for(int i=K; i>=1; i--){ + caseK = i; + checkAcc=0; + for(int i=currAcc+caseK; i>=0; i=i-K){ + checkAcc = checkAcc + i; + } + if(checkAcc <= dist){ + acc.push(currAcc+caseK); + dist = dist - (currAcc + caseK); + accFlag = true; + break; + } + } + + // accel is unavailable + if(!accFlag){ + // maintain current acc + checkAcc = 0; + for(int i=currAcc; i>=0; i=i-K){ + checkAcc = checkAcc + i; + } + if(checkAcc <= dist){ + acc.push(currAcc); + dist = dist - currAcc; + accFlag = true; + } + // decel is needed + else{ + checkAcc = 0; + caseK = 0; + for(int i=1; i<=K; i++){ + caseK = i; + checkAcc=0; // 이거 안하면 무한 loop.. + for(int i=currAcc-caseK; i>=0; i=i-K){ + checkAcc = checkAcc + i; + } + if(checkAcc <= dist){ + acc.push(currAcc-caseK); + dist = dist - (currAcc - caseK); + break; + } + } + } + } + } + + cout << "size: " << acc.size() << endl; +} + +int main(){ + sol(23, 2); // ans: 6 + acc = stack(); + sol(9, 2); // ans: 3 + acc = stack(); + sol(10, 1); // ans: 5 +} \ No newline at end of file diff --git a/gaeun/programmers/function_develop.cpp b/gaeun/programmers/function_develop.cpp new file mode 100644 index 0000000..60f2411 --- /dev/null +++ b/gaeun/programmers/function_develop.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include + +using namespace std; + +vector solution(vector progresses, vector speeds) { + vector answer; + queue days; + for(int i=0; i= days.front()){ + days.pop(); + distributeDays++; + printf("# here\n"); + printf("days.size(): %d\n",days.size()); + } + if(days.empty()){ + break; + } + answer.push_back(distributeDays); + distribute = days.front(); + days.pop(); + distributeDays = 1; + printf("## here\n"); + printf("days.size(): %d\n",days.size()); + } + answer.push_back(distributeDays); + printf("### here\n"); + printf("days.size(): %d\n",days.size()); + + return answer; +} + +int main(){ + vector p1 = {95, 90, 99, 99, 80, 99}; + vector s1 = {1, 1, 1, 1, 1, 1}; + vector ans; + ans = solution(p1, s1); + for(int i=0; i +#include +#include +#include +#include +#include + +using namespace std; + +// path, + +set> visited; +int bfs(const string& start, int zero) { + + + set> visited; + queue, int>> que; + int dr[] = {1, -1, 0, 0}; + int dc[] = {0, 0, 1, -1}; + + const string ans = "123456780"; + + que.push({{start, zero}, 0}); + visited.insert({start, zero}); + + while(!que.empty()) { + string cur = que.front().first.first; + + int z = que.front().first.second; + int dep = que.front().second; + que.pop(); + + if(cur == ans) { + return dep; + } + + int r = z / 3; + int c = z % 3; + + for(int i = 0; i < 4; i++) { + int nr = r + dr[i]; + int nc = c + dc[i]; + + if(nr < 0 || nr > 2 || nc < 0 || nc > 2) + continue; + + int nz = nr * 3 + nc; + string next = cur; + swap(next[z], next[nz]); + + if(visited.find({next, nz}) != visited.end()){ + continue; + } + + + que.push( {{next, nz}, dep + 1}); + visited.insert({next, nz}); + } + } + + return -1; +} + + + +int main() { + // 문제는 bfs -> 완전탐색 + vector board; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + string temp; + cin >> temp; + board.push_back(temp); + } + } + + string initial_state; + int zero_idx; + for (int i = 0; i < 9; i++) { + if (board[i] == "0") { + zero_idx = i; + } + initial_state += board[i]; + } + + cout << bfs(initial_state, zero_idx) << endl; + + + return 0; +} \ No newline at end of file diff --git a/hose/09/19583/main.cpp b/hose/09/19583/main.cpp new file mode 100644 index 0000000..8f72d12 --- /dev/null +++ b/hose/09/19583/main.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +int toMinutes(const std::string& inTime) +{ + // 00:00 + int hours = std::stoi(inTime.substr(0, 2)); + int minutes = std::stoi(inTime.substr(3, 2)); + return hours * 60 + minutes; +} + +int main() +{ + std::string start_meeting_time; + std::string end_meeting_time; + std::string end_streaming_time; + + std::cin >> start_meeting_time >> end_meeting_time >> end_streaming_time; + std::cin.ignore(); + + int start_meeting_minutes = toMinutes(start_meeting_time); + int end_meeting_minutes = toMinutes(end_meeting_time); + int end_streaming_minutes = toMinutes(end_streaming_time); + + std::string chat; + std::string time, name; + std::unordered_map m; + + int result = 0; + + while (std::getline(std::cin, chat)) + { + std::istringstream iss(chat); + iss >> time >> name; + + int chat_time_minutes = toMinutes(time); + + if (chat_time_minutes > end_streaming_minutes) + { + break; + } + + if (chat_time_minutes <= start_meeting_minutes) + { + m[name]++; + continue; + } + + if (chat_time_minutes >= end_meeting_minutes) + { + if (m.find(name) != m.end()) + { + m.erase(name); + result++; + } + } + } + + std::cout << result << std::endl; + + return 0; +} \ No newline at end of file diff --git a/hose/10/1715/main.cpp b/hose/10/1715/main.cpp new file mode 100644 index 0000000..2e562c3 --- /dev/null +++ b/hose/10/1715/main.cpp @@ -0,0 +1,39 @@ +#include +#include +#include + +using namespace std; + +int main() { + + priority_queue, greater> pq; + int n = 0; + cin >> n; + + int res = 0; + + for (int i = 0; i < n; ++i) { + int m = 0; + cin >> m; + pq.push(m); + } + + if (n == 1) { + cout << 0 << endl; + return 0; + } + + for (int i = 0; i < n-1 ; ++i) { + int a = pq.top(); + pq.pop(); + int b = pq.top(); + pq.pop(); + pq.push(a+b); + + res += a+b; + } + + + cout << res << endl; + return 0; +} \ No newline at end of file diff --git a/hose/10/5427/main.cpp b/hose/10/5427/main.cpp new file mode 100644 index 0000000..edd8e30 --- /dev/null +++ b/hose/10/5427/main.cpp @@ -0,0 +1,107 @@ +#include +#include +#include +#include + +using namespace std; + +int number_case; + +int width; +int height; + +queue> fire; + +char map[1000][1000]; +bool visited[1000][1000]; + +int dr[4] = { -1, 1, 0 , 0 }; +int dc[4] = { 0, 0, 1, -1 }; + +string bfs(pair start, queue> fire, bool visited[1000][1000]) { + queue, int>> q; + visited[start.first][start.second] = true; + q.push({ start, 0 }); + + + while (!q.empty()) { + + int fire_size = fire.size(); + for (int i = 0; i < fire_size; ++i) { + int fire_r = fire.front().first; + int fire_c = fire.front().second; + + fire.pop(); + + for (int j = 0; j < 4; ++j) { + int next_fire_r = fire_r + dr[j]; + int next_fire_c = fire_c + dc[j]; + + if (next_fire_r < 0 || next_fire_r == height || next_fire_c < 0 || next_fire_c == width) { + continue; + } + + if (map[next_fire_r][next_fire_c] == '.') { + map[next_fire_r][next_fire_c] = '*'; + fire.push({ next_fire_r, next_fire_c }); + } + } + } + + int q_size = q.size(); + for (int i = 0; i < q_size; ++i) { + int r = q.front().first.first; + int c = q.front().first.second; + int dep = q.front().second; + q.pop(); + + for (int i = 0; i < 4; ++i) { + int next_r = r + dr[i]; + int next_c = c + dc[i]; + + if (next_r < 0 || next_r == height || next_c < 0 || next_c == width) { + return to_string(dep + 1); + } + + if (map[next_r][next_c] == '*' || map[next_r][next_c] == '#' || visited[next_r][next_c]) { + continue; + } + + visited[next_r][next_c] = true; + q.push({ {next_r, next_c}, dep + 1 }); + } + } + } + + return "IMPOSSIBLE"; +} + +int main() { + ios::sync_with_stdio(0); + cin.tie(0); + + cin >> number_case; + + pair start; + for (int i = 0; i < number_case; ++i) { + cin >> width >> height; + + for (int j = 0; j < height; ++j) { + for (int k = 0; k < width; ++k) { + cin >> map[j][k]; + + if (map[j][k] == '@') { + start = { j, k }; + map[j][k] = '.'; + } + else if (map[j][k] == '*') { + fire.push({ j, k }); + } + } + } + + cout << bfs(start, fire, visited) << '\n'; + } + + return 0; +} \ No newline at end of file diff --git a/hose/11/1052/main.cpp b/hose/11/1052/main.cpp new file mode 100644 index 0000000..55bb85c --- /dev/null +++ b/hose/11/1052/main.cpp @@ -0,0 +1,19 @@ +#include +#include + +int main() { + int n, k; + std::cin >> n >> k; + + long long result = 0; + + while (__builtin_popcount(n) > k) { + int first_one_index = __builtin_ctz(n); + result += (1LL << first_one_index); + n += (1 << first_one_index); + } + + std::cout << result << std::endl; + + return 0; +} \ No newline at end of file diff --git a/hose/11/12764/main.cpp b/hose/11/12764/main.cpp new file mode 100644 index 0000000..9e74f53 --- /dev/null +++ b/hose/11/12764/main.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include + +using namespace std; + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + int N; + cin >> N; + + vector>> events; + for (int i = 0; i < N; i++) { + int start, end; + cin >> start >> end; + events.push_back({start, {"Start", i}}); + events.push_back({end, {"End", i}}); + } + + sort(events.begin(), events.end()); + + priority_queue, greater> pq_pc; + vector pc_info_list(N, 0); + vector person_idx2pc(N, -1); + int now_pc = 0; + + for (const auto& event : events) { + int time = event.first; + string type = event.second.first; + int idx = event.second.second; + + if (type == "Start") { + int pc; + if (!pq_pc.empty()) { + pc = pq_pc.top(); + pq_pc.pop(); + } else { + pc = now_pc++; + } + pc_info_list[pc]++; + person_idx2pc[idx] = pc; + } else { + int pc = person_idx2pc[idx]; + pq_pc.push(pc); + } + } + + cout << now_pc << "\n"; + for (int i = 0; i < now_pc; i++) { + cout << pc_info_list[i] << " "; + } + cout << "\n"; + + return 0; +} \ No newline at end of file diff --git a/hose/11/1781/main.cpp b/hose/11/1781/main.cpp new file mode 100644 index 0000000..ff1ddb0 --- /dev/null +++ b/hose/11/1781/main.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include + +using namespace std; + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + int N; + cin >> N; + + vector> deadline_list(N + 1); + + for (int i = 0; i < N; i++) { + int deadline, score; + cin >> deadline >> score; + deadline_list[deadline].push_back(score); + } + + priority_queue pq; + long long ans = 0; + + for (int deadline = N; deadline > 0; deadline--) { + for (int score : deadline_list[deadline]) { + pq.push(score); + } + if (!pq.empty()) { + ans += pq.top(); + pq.pop(); + } + } + + cout << ans << "\n"; + + return 0; +} \ No newline at end of file diff --git a/hose/12/17825/17825/17825.cpp b/hose/12/17825/17825/17825.cpp new file mode 100644 index 0000000..b554381 --- /dev/null +++ b/hose/12/17825/17825/17825.cpp @@ -0,0 +1,104 @@ +// 17825.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include + +using namespace std; + +int dice[10]; + +int horse[4]; + +int board[33]; + +int result = 0; + +void dfs(int cnt, int sum) +{ + if (cnt == 10) + { + if (result < sum) + { + result = sum; + } + return; + } + + for (int i = 0; i < 4; i++) + { + int cur = horse[i]; + int next = cur; + int move = dice[cnt]; + + + if (cur == 5 || cur == 10 || cur == 15) + { + next = board[cur]; + move--; + } + + while (move--) + { + next = board[next]; + } + + if (next != 21 && board[next] != 21) + { + bool flag = true; + for (int j = 0; j < 4; j++) + { + if (i != j && horse[j] == next) + { + flag = false; + break; + } + } + + if (flag) + { + horse[i] = next; + dfs(cnt + 1, sum + board[next]); + horse[i] = cur; + } + } + else + { + horse[i] = next; + dfs(cnt + 1, sum); + horse[i] = cur; + } + } +} + +int main() +{ + for (int i = 0; i < 10; i++) + { + cin >> dice[i]; + } + + for (int i = 0; i <= 20; i++) + { + board[i] = i + 1; + } + + board[21] = 21; + board[22] = 23; + board[23] = 24; + board[24] = 30; + board[25] = 26; + board[26] = 30; + board[27] = 28; + board[28] = 29; + board[29] = 30; + board[30] = 31; + board[31] = 32; + board[32] = 20; + + dfs(0, 0); + + cout << result << endl; + + return 0; +} + diff --git a/hose/12/2110/2110/2110.cpp b/hose/12/2110/2110/2110.cpp new file mode 100644 index 0000000..ef77b97 --- /dev/null +++ b/hose/12/2110/2110/2110.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +using namespace std; + +// 처음에 조합으로 풀었으나 시간초과로 실패 +// 집 위치로 이분탐색 하는 것이 아닌 거리로 + +int main() { + + ios_base::sync_with_stdio(false); + cin.tie(0); + cout.tie(0); + int n, k; + + cin >> n >> k; + + + vector v(n); + + for (int i = 0; i < n; i++) { + cin >> v[i]; + } + + sort(v.begin(), v.end()); + + // 최소거리 + int min_di = 1; + // 최대거리 + int max_di = v[n - 1] - v[0]; + + while (min_di <= max_di) { + int mid_di = (min_di + max_di) / 2; + + int count = 1; + int start = v[0]; + + for (int i = 1; i < n; i++) { + if (v[i] - start >= mid_di) { + count++; + start = v[i]; + } + } + + if (count >= k) { + min_di = mid_di + 1; + } + else { + max_di = mid_di - 1; + } + + } + + cout << max_di << '\n'; + + return 0; +} \ No newline at end of file diff --git a/hose/12/2352/main b/hose/12/2352/main new file mode 100755 index 0000000..a8c0ab4 Binary files /dev/null and b/hose/12/2352/main differ diff --git a/hose/12/2352/main.cpp b/hose/12/2352/main.cpp new file mode 100644 index 0000000..dad3acb --- /dev/null +++ b/hose/12/2352/main.cpp @@ -0,0 +1,62 @@ +#include +#include +using namespace std; + +// 오름차순이 아니면 선 끊김 +// 가장 긴 수열 찾기 -> lis +// lowerbound라는 멋진 함수 이용하기 + +int arr[40001]; + +int main() { + + ios::sync_with_stdio(0); + cin.tie(0); + cout.tie(0); + + int n; + cin >> n; + + vector arr_index; + + for(int i = 0; i < n; i++) { + cin >> arr[i]; + } + + vector v; + v.push_back(arr[0]); + + for (int i = 1; i < n; ++i) { + if (v.back() < arr[i]) { + v.push_back(arr[i]); + + } else { + auto it = lower_bound(v.begin(), v.end(), arr[i]); + v[it - v.begin()] = arr[i]; + } + } + + cout << v.size() << '\n'; + + for (int i = 0; i < n; i++) { + cout << arr_index[i] << ' '; + } + + return 0; +} + +// lower bound: 찾고자 하는 값 이상이 처음 나오는 위치. +// 4 2 6 3 1 5 +// 2, 3, 5 + +// LIS: 4 // index[0] = 1 +// LIS: 2 // index[1] = 1 +// 2 6: // index[2] = 2 +// 2 3 // index[3] = 2 +// 1 3 // index[4] = 1 +// 1 3 5 index[5] = 3 + + + +// index[5], index[3], index[1] +// 5 3 2 뒤집어. diff --git a/hose/13/2839/2839/2839.cpp b/hose/13/2839/2839/2839.cpp new file mode 100644 index 0000000..44f7ee4 --- /dev/null +++ b/hose/13/2839/2839/2839.cpp @@ -0,0 +1,50 @@ +#include + +int main() { + int number = 0; + int index = 0; + double count = 0; + int fiveKg = -1; + int threeKg = -1; + int result = 0; + + + scanf("%d", &number); + + if (number < 3 || number>5000) return 0; + + if (number % 5 == 0) + { + printf("%d\n", number / 5); + } + else + { + while (1) + { + count = (double)(number - (5 * index)) / 3;// īƮ ? + if (count - (int)count == 0) + { + fiveKg = index; + threeKg = (int)count; + } + + index++; + if (number - (5 * index) < 3) break; + } + + if (fiveKg == -1 && threeKg == -1) + { + printf("-1\n"); + } + else if (fiveKg == -1 && threeKg != -1) + { + printf("%d\n", threeKg); + } + else + { + printf("%d\n", fiveKg + threeKg); + } + } + + return 0; +} diff --git a/hose/13/GenoQuery/GenoQuery/GenoQuery.cpp b/hose/13/GenoQuery/GenoQuery/GenoQuery.cpp new file mode 100644 index 0000000..7f070ba --- /dev/null +++ b/hose/13/GenoQuery/GenoQuery/GenoQuery.cpp @@ -0,0 +1,35 @@ +#include +#include +#include + +std::vector solution(std::string& S, std::vector& P, std::vector& Q) { + int N = S.length(); + std::vector> prefixSum(4, std::vector(N + 1, 0)); + + // Calculate prefix sums for A, C, G, T + for (int i = 0; i < N; i++) { + prefixSum[0][i + 1] = prefixSum[0][i] + (S[i] == 'A'); + prefixSum[1][i + 1] = prefixSum[1][i] + (S[i] == 'C'); + prefixSum[2][i + 1] = prefixSum[2][i] + (S[i] == 'G'); + prefixSum[3][i + 1] = prefixSum[3][i] + (S[i] == 'T'); + } + + std::vector result; + for (size_t i = 0; i < P.size(); i++) { + int start = P[i], end = Q[i] + 1; + if (prefixSum[0][end] - prefixSum[0][start] > 0) { + result.push_back(1); // A found + } + else if (prefixSum[1][end] - prefixSum[1][start] > 0) { + result.push_back(2); // C found + } + else if (prefixSum[2][end] - prefixSum[2][start] > 0) { + result.push_back(3); // G found + } + else { + result.push_back(4); // Only T remains + } + } + + return result; +} \ No newline at end of file diff --git a/hose/13/main.cpp b/hose/13/main.cpp new file mode 100644 index 0000000..77b8cce --- /dev/null +++ b/hose/13/main.cpp @@ -0,0 +1,73 @@ +#include +#include +#include + +using namespace std; + +// 하나의 널빤지를 고정하는데 필요한 최소 인덱스의 못 찾기 +int minNails(int plankStart, int plankEnd, const std::vector>& sortedC, int prev) +{ + int start = 0, end = sortedC.size() - 1, mid = 0; + int minIdx = -1; // 조건 만족하기 시작하는 nail idx + + + // 널빤지의 시작점 이상이면서 가장 왼쪽에 있는 못 찾기 -> Lowerbound로 찾을 수 있을까? + while (start <= end) { + mid = (start + end) / 2; + if (sortedC[mid].first < plankStart) { + start = mid + 1; + } else if (sortedC[mid].first > plankEnd) { + end = mid - 1; + } else { + minIdx = mid; + end = mid - 1; + } + } + + // 조건 만족하는 nail이 없다 + if (minIdx == -1) { + return -1; + } + + // 최소 인덱스의 못 찾기 + // 정렬전 C배열에서의 인덱스 + int minOrgIdx = sortedC[minIdx].second; + for (int i = minIdx; i < sortedC.size(); i++) { + // 널빤지의 끝점을 넘어섰음 루프 탈출 + if (sortedC[i].first > plankEnd) + break; + minOrgIdx = std::min(sortedC[i].second, minOrgIdx); + if (minOrgIdx <= prev) { + return prev; + } + } + + return minOrgIdx; + } + +int solution(vector &A, vector &B, vector &C) { + int N = A.size(); + int M = C.size(); + std::vector> sortedC(M); + + for (int i = 0; i < M; i++) { + sortedC[i] = {C[i], i}; + } + + std::sort(sortedC.begin(), sortedC.end()); + + // 한 널빤지의 못 사용 최소 개수 구하기 + int result = 0, numberOfNails = 0; + for (int i = 0; i < N; i++) + { + numberOfNails = minNails(A[i], B[i], sortedC, result); + if (numberOfNails == -1) + return -1; + + // 모든 못을 커버하는 최대 구하기 + result = std::max(result, numberOfNails); + } + + return result + 1; + +} \ No newline at end of file diff --git a/hose/14/1149/1149/1149.cpp b/hose/14/1149/1149/1149.cpp new file mode 100644 index 0000000..3df1d24 --- /dev/null +++ b/hose/14/1149/1149/1149.cpp @@ -0,0 +1,86 @@ +// 1149.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include +#include +using namespace std; + + +// 우리가 구하고 싶은 것 +// an을 구하는 것. n은 1 ~ 1000 + +// 1. +// 만약 an에 red를 칠하고 싶다면 an = an-1 + red +// 이 경우에 an-1 = min(an-2 + green, an-2 + blue) + +// 2. +// 만약 an에 green을 칠하고 싶다면 an = an-1 + green +// 이 경우에 an-1 = min(an-2 + red, an-2 + blue) + +// 3. +// 만약 an에 blue를 칠하고 싶다면 an = an-1 + blue +// 이 경우에 an-1 = min(an-2 + red, an-2 + green) + +// an = 위 세가지 경우에서 최소값을 선택하면 됨. + + +// 미지수 x에 대하여 ax가 r인 경우, g인 경우, b인 경우 모두 구해야함. +// 그래서 n by 3 배열을 만들어야함. + +// 정의 +// n번째 집에 red를 칠할 때 a[n-1][0] + r +// n번째 집에 green을 칠할 때 a[n-1][1] + g +// n번째 집에 blue를 칠할 때 a[n-1][2] + b + + +// n-1 번째 집에 red를 칠할 때 a[n-2][1] + r +// n-1 번째 집에 green을 칠할 때 a[n-2][0] + g +// n-1 번째 집에 blue를 칠할 때 a[n-2][2] + b + +/// ... + +// a[1][0] = 2번째 집에 red를 칠할 때 +// a[1][1] = 2번째 집에 green을 칠할 때 +// a[1][2] = 2번째 집에 blue를 칠할 때 + +// 그러면 a[1][0]의 값은 어떻게 구해야하나. +// a[1][0] = min(a[0][1], a[0[2]]) + r + + + + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL); + + int N = 0; + cin >> N; + + // N by 3 mertix + int** arr = new int* [N]; + + for (int i = 0; i < N; ++i) + { + arr[i] = new int[3]; + + if (i == 0) + { + cin >> arr[i][0] >> arr[i][1] >> arr[i][2]; + continue; + } + + int r, g, b; + cin >> r >> g >> b; + + arr[i][0] += min(arr[i - 1][1], arr[i - 1][2]) + r; + arr[i][1] += min(arr[i - 1][0], arr[i - 1][2]) + g; + arr[i][2] += min(arr[i - 1][0], arr[i - 1][1]) + b; + } + + int result = min(arr[N - 1][0], min(arr[N - 1][1], arr[N - 1][2])); + cout << result << endl; + + return 0; +} \ No newline at end of file diff --git a/hose/15/2225.cpp b/hose/15/2225.cpp new file mode 100644 index 0000000..662b2ff --- /dev/null +++ b/hose/15/2225.cpp @@ -0,0 +1,32 @@ +#include + +using namespace std; + +const int MOD = 1000000000; + +int main() { + int N, K; + cin >> N >> K; + + // 2차원 배열 선언 + int dp[201][201] = {0}; + + // 초기 조건: dp[0][k] = 1 (0을 k개의 숫자로 만드는 방법은 1가지) + for (int k = 1; k <= K; ++k) { + dp[0][k] = 1; + } + + // dp 테이블 채우기 + for (int n = 1; n <= N; ++n) { + for (int k = 1; k <= K; ++k) { + + // k개의 숫자로 n을 만드는 방법 = k-1개의 숫자로 n을 만드는 방법 + k개의 숫자로 n-1을 만드는 방법 + dp[n][k] = (dp[n-1][k] + dp[n][k-1]) % MOD; + } + } + + // 결과 출력 + cout << dp[N][K] << endl; + + return 0; +} diff --git a/hose/src/4485/4485/4485.cpp b/hose/src/4485/4485/4485.cpp new file mode 100644 index 0000000..ef03232 --- /dev/null +++ b/hose/src/4485/4485/4485.cpp @@ -0,0 +1,177 @@ +// 4485.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include +#include +#include +#include + + +using namespace std; + +/* + ӿ ȭ (rupee). ׷ Ȥ 'Ϸ' Ҹ ǵ ϴµ, ̰ ȹϸ ǰ ϰ ȴ! + + ø ΰ, ũ ϷǸ N x N ũ ִ. [0][0] ĭ̱⵵ ϴ. + ̷ Գİ ´ٸ ۿ ڲ " ְ ?" ñ ̴. +ũ ΰ̰ ٴ ׳ ִ ε, ŸƲ ٰ ִٰ ڲ ̷ ϴϱ ź ɸ ⿡ ̴. + +Ͽư ...ƴ ũ ݴ ⱸ, Ʒ ĭ [N-1][N-1] ̵ؾ Ѵ. ĭ Ϸǰ ִµ, ĭ ش Ϸ ũ⸸ŭ Ұ ȴ. +ũ Ҵ ݾ ּҷ Ͽ dz ̵ؾ ϸ, ¿ 1ĭ ̵ ִ. + +ũ ۿ ּ ݾ ϱ? + + + +Է + +Է ׽Ʈ ̽ ̷ ִ. + + ׽Ʈ ̽ ù° ٿ ũ⸦ Ÿ N ־. (2 N 125) N = 0 Է ־ ü Է ȴ. + +̾ N ٿ ĭ ִ Ϸ ũⰡ еǾ ʴ ־. + +Ϸ ũⰡ k ĭ kǸ Ҵ´ٴ ̴. ⼭ ־ 0 ̻ 9 ڸ . + + + + + + ׽Ʈ ̽ ٿ Ŀ 缭 Ѵ. Ͻÿ. + + + Է 1 +3 +5 5 4 +3 9 1 +3 2 7 +5 +3 7 2 0 1 +2 8 0 9 1 +1 2 1 8 1 +9 8 9 2 0 +3 6 5 1 5 +7 +9 0 5 1 1 5 3 +4 1 2 1 6 5 3 +0 7 6 1 6 8 5 +1 1 7 8 3 2 3 +9 4 0 7 6 4 1 +5 8 3 2 4 8 3 +7 4 8 4 8 3 4 +0 + + + +Problem 1: 20 +Problem 2: 19 +Problem 3: 36 + + + +*/ + + +#define INT_MAX 2147483647 + +int N; +int board[125][125]; +int cost[125][125] = { INT_MAX, }; +bool visited[125][125] = { false, }; + +int dr[] = { 0, 0, 1, -1 }; +int dc[] = { 1, -1, 0, 0 }; + + + +struct CompareNode { + bool operator()(const pair, int>& a, + const pair, int>& b) const { + return a.second > b.second; + } +}; + + + +void dijkstra() +{ + + // ġ, + + priority_queue, int>, + vector, int>>, + CompareNode> pq; + + + pq.push({ {0, 0}, board[0][0] }); + + cost[0][0] = board[0][0]; + + while (!pq.empty()) + { + int r = pq.top().first.first; + int c = pq.top().first.second; + + int curCost = pq.top().second; + + pq.pop(); + + if (visited[r][c]) + continue; + + visited[r][c] = true; + + for (int i = 0; i < 4; i++) + { + int nr = r + dr[i]; + int nc = c + dc[i]; + + if (nr < 0 || nc < 0 || nr >= N || nc >= N) + continue; + + if (cost[nr][nc] > curCost + board[nr][nc]) + { + cost[nr][nc] = curCost + board[nr][nc]; + pq.push({ {nr, nc}, cost[nr][nc] }); + } + } + } + +} + + + + + +int main() +{ + + int problem = 1; + + while (1) + { + cin >> N; + + if (N == 0) + break; + + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + cin >> board[i][j]; + cost[i][j] = INT_MAX; + visited[i][j] = false; + } + } + + dijkstra(); + + cout << "Problem " << problem << ": " << cost[N - 1][N - 1] << endl; + + problem++; + } + + return 0; + +} \ No newline at end of file diff --git a/jihyeon/AlgorithmStudyS8JH/.gitignore b/jihyeon/AlgorithmStudyS8JH/.gitignore new file mode 100644 index 0000000..dd1356b --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/.gitignore @@ -0,0 +1,38 @@ +### macOS ### +*.DS_Store +.AppleDouble +.LSOverride + +### Swift ### +# Xcode + +## Build generated +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +## Projects ## +**/*.xcodeproj +**/*.xcworkspace \ No newline at end of file diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.pbxproj b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.pbxproj new file mode 100644 index 0000000..d225031 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.pbxproj @@ -0,0 +1,407 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + B8A7D2742C4E411D00B4BF87 /* 7_23_Document.docc in Sources */ = {isa = PBXBuildFile; fileRef = B8A7D2732C4E411D00B4BF87 /* 7_23_Document.docc */; }; + B8B1C6EC2C9EAF350093647C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8B1C6EB2C9EAF350093647C /* main.swift */; }; + B8D7469B2C368B85007AF3E2 /* HeapAndPQ.docc in Sources */ = {isa = PBXBuildFile; fileRef = B8D7469A2C368B85007AF3E2 /* HeapAndPQ.docc */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + B889E0652C33C2AC00809148 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = /usr/share/man/man1/; + dstSubfolderSpec = 0; + files = ( + ); + runOnlyForDeploymentPostprocessing = 1; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + B84B00212C60899700BE24A6 /* boj_17825.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_17825.swift; sourceTree = ""; }; + B84B00232C61008600BE24A6 /* boj_2352.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_2352.swift; sourceTree = ""; }; + B8699B962C87274E00A18058 /* boj_12865.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_12865.swift; sourceTree = ""; }; + B889E0672C33C2AC00809148 /* AlgorithmStudyS8JH */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = AlgorithmStudyS8JH; sourceTree = BUILT_PRODUCTS_DIR; }; + B889E06A2C33C2AC00809148 /* boj_19583.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_19583.swift; sourceTree = ""; }; + B889E0722C33F4AA00809148 /* boj_1525.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_1525.swift; sourceTree = ""; }; + B8975B642C7B186900BC48DB /* boj_11727.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_11727.swift; sourceTree = ""; }; + B8975B662C7CA2EB00BC48DB /* boj_2156.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_2156.swift; sourceTree = ""; }; + B8975B682C7CC40100BC48DB /* boj_1149.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_1149.swift; sourceTree = ""; }; + B8A7D2732C4E411D00B4BF87 /* 7_23_Document.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = 7_23_Document.docc; sourceTree = ""; }; + B8A7D2752C4E4AAE00B4BF87 /* programmers_n+1카드게임.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "programmers_n+1카드게임.swift"; sourceTree = ""; }; + B8B1C6EB2C9EAF350093647C /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + B8CA3C1E2C74919F00B4B31A /* boj_2839.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_2839.swift; sourceTree = ""; }; + B8D746952C3681D9007AF3E2 /* boj_1715.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_1715.swift; sourceTree = ""; }; + B8D7469A2C368B85007AF3E2 /* HeapAndPQ.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = HeapAndPQ.docc; sourceTree = ""; }; + B8E2E5612C6B44FD0096E90C /* programmers_입국심사.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "programmers_입국심사.swift"; sourceTree = ""; }; + B8EFF6A22C464F3100E67E15 /* boj_1052.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = boj_1052.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + B889E0642C33C2AC00809148 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + B84B00202C60898F00BE24A6 /* 8.3 */ = { + isa = PBXGroup; + children = ( + B84B00212C60899700BE24A6 /* boj_17825.swift */, + B84B00232C61008600BE24A6 /* boj_2352.swift */, + ); + path = 8.3; + sourceTree = ""; + }; + B8699B952C87274500A18058 /* 9.3 */ = { + isa = PBXGroup; + children = ( + B8699B962C87274E00A18058 /* boj_12865.swift */, + ); + path = 9.3; + sourceTree = ""; + }; + B889E05E2C33C2AC00809148 = { + isa = PBXGroup; + children = ( + B889E0692C33C2AC00809148 /* AlgorithmStudyS8JH */, + B889E0682C33C2AC00809148 /* Products */, + ); + sourceTree = ""; + }; + B889E0682C33C2AC00809148 /* Products */ = { + isa = PBXGroup; + children = ( + B889E0672C33C2AC00809148 /* AlgorithmStudyS8JH */, + ); + name = Products; + sourceTree = ""; + }; + B889E0692C33C2AC00809148 /* AlgorithmStudyS8JH */ = { + isa = PBXGroup; + children = ( + B8B1C6EA2C9EAF0E0093647C /* 9.21 */, + B8699B952C87274500A18058 /* 9.3 */, + B8975B632C7B185E00BC48DB /* 8.27 */, + B8CA3C1D2C74918100B4B31A /* 8.20 */, + B8E2E5602C6B44EF0096E90C /* 8.13 */, + B84B00202C60898F00BE24A6 /* 8.3 */, + B8A7D2722C4E40BC00B4BF87 /* 7.23 */, + B8EFF6A12C4642B500E67E15 /* 7.16 */, + B8D746942C3681D1007AF3E2 /* 7.9 */, + B889E0712C33C2BC00809148 /* 7.2 */, + ); + path = AlgorithmStudyS8JH; + sourceTree = ""; + }; + B889E0712C33C2BC00809148 /* 7.2 */ = { + isa = PBXGroup; + children = ( + B889E06A2C33C2AC00809148 /* boj_19583.swift */, + B889E0722C33F4AA00809148 /* boj_1525.swift */, + ); + path = 7.2; + sourceTree = ""; + }; + B8975B632C7B185E00BC48DB /* 8.27 */ = { + isa = PBXGroup; + children = ( + B8975B642C7B186900BC48DB /* boj_11727.swift */, + B8975B662C7CA2EB00BC48DB /* boj_2156.swift */, + B8975B682C7CC40100BC48DB /* boj_1149.swift */, + ); + path = 8.27; + sourceTree = ""; + }; + B8A7D2722C4E40BC00B4BF87 /* 7.23 */ = { + isa = PBXGroup; + children = ( + B8A7D2732C4E411D00B4BF87 /* 7_23_Document.docc */, + B8A7D2752C4E4AAE00B4BF87 /* programmers_n+1카드게임.swift */, + ); + path = 7.23; + sourceTree = ""; + }; + B8B1C6EA2C9EAF0E0093647C /* 9.21 */ = { + isa = PBXGroup; + children = ( + B8B1C6EB2C9EAF350093647C /* main.swift */, + ); + path = 9.21; + sourceTree = ""; + }; + B8CA3C1D2C74918100B4B31A /* 8.20 */ = { + isa = PBXGroup; + children = ( + B8CA3C1E2C74919F00B4B31A /* boj_2839.swift */, + ); + path = 8.20; + sourceTree = ""; + }; + B8D746942C3681D1007AF3E2 /* 7.9 */ = { + isa = PBXGroup; + children = ( + B8D746952C3681D9007AF3E2 /* boj_1715.swift */, + B8D7469A2C368B85007AF3E2 /* HeapAndPQ.docc */, + ); + path = 7.9; + sourceTree = ""; + }; + B8E2E5602C6B44EF0096E90C /* 8.13 */ = { + isa = PBXGroup; + children = ( + B8E2E5612C6B44FD0096E90C /* programmers_입국심사.swift */, + ); + path = 8.13; + sourceTree = ""; + }; + B8EFF6A12C4642B500E67E15 /* 7.16 */ = { + isa = PBXGroup; + children = ( + B8EFF6A22C464F3100E67E15 /* boj_1052.swift */, + ); + path = 7.16; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + B889E0662C33C2AC00809148 /* AlgorithmStudyS8JH */ = { + isa = PBXNativeTarget; + buildConfigurationList = B889E06E2C33C2AC00809148 /* Build configuration list for PBXNativeTarget "AlgorithmStudyS8JH" */; + buildPhases = ( + B889E0632C33C2AC00809148 /* Sources */, + B889E0642C33C2AC00809148 /* Frameworks */, + B889E0652C33C2AC00809148 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = AlgorithmStudyS8JH; + productName = AlgorithmStudyS8JH; + productReference = B889E0672C33C2AC00809148 /* AlgorithmStudyS8JH */; + productType = "com.apple.product-type.tool"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + B889E05F2C33C2AC00809148 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1430; + LastUpgradeCheck = 1430; + TargetAttributes = { + B889E0662C33C2AC00809148 = { + CreatedOnToolsVersion = 14.3.1; + LastSwiftMigration = 1430; + }; + }; + }; + buildConfigurationList = B889E0622C33C2AC00809148 /* Build configuration list for PBXProject "AlgorithmStudyS8JH" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = B889E05E2C33C2AC00809148; + productRefGroup = B889E0682C33C2AC00809148 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + B889E0662C33C2AC00809148 /* AlgorithmStudyS8JH */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + B889E0632C33C2AC00809148 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B8A7D2742C4E411D00B4BF87 /* 7_23_Document.docc in Sources */, + B8D7469B2C368B85007AF3E2 /* HeapAndPQ.docc in Sources */, + B8B1C6EC2C9EAF350093647C /* main.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + B889E06C2C33C2AC00809148 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 13.3; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + B889E06D2C33C2AC00809148 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 13.3; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + B889E06F2C33C2AC00809148 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = B849TJY5N4; + ENABLE_HARDENED_RUNTIME = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + B889E0702C33C2AC00809148 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = B849TJY5N4; + ENABLE_HARDENED_RUNTIME = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + B889E0622C33C2AC00809148 /* Build configuration list for PBXProject "AlgorithmStudyS8JH" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B889E06C2C33C2AC00809148 /* Debug */, + B889E06D2C33C2AC00809148 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B889E06E2C33C2AC00809148 /* Build configuration list for PBXNativeTarget "AlgorithmStudyS8JH" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B889E06F2C33C2AC00809148 /* Debug */, + B889E0702C33C2AC00809148 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = B889E05F2C33C2AC00809148 /* Project object */; +} diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/xcuserdata/kimjihyeon.xcuserdatad/UserInterfaceState.xcuserstate b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/xcuserdata/kimjihyeon.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..120bebb Binary files /dev/null and b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/project.xcworkspace/xcuserdata/kimjihyeon.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/xcuserdata/kimjihyeon.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/xcuserdata/kimjihyeon.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..9cf36ab --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/xcuserdata/kimjihyeon.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,6 @@ + + + diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/xcuserdata/kimjihyeon.xcuserdatad/xcschemes/xcschememanagement.plist b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/xcuserdata/kimjihyeon.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..f14947e --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH.xcodeproj/xcuserdata/kimjihyeon.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + AlgorithmStudyS8JH.xcscheme_^#shared#^_ + + orderHint + 0 + + + + diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.16/boj_1052.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.16/boj_1052.swift new file mode 100644 index 0000000..fee5ede --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.16/boj_1052.swift @@ -0,0 +1,50 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 2024/07/16. +// + +import Foundation + +// 시도1. 시간초과 남 +/* +let input = readLine()!.components(separatedBy: " ").map { Int($0)! } +var N = input[0] +let K = input[1] + +var answer = 0 +// 매번 2진수로 변환해서 1의 개수가 K개를 초과하는지 확인 +// N이 최대 10^7 이므로 초과 +while String(N, radix: 2).filter({ $0 == "1" }).count > K { + answer += 1 + N += 1 +} +print(answer) + */ + +// 시도2. +let input = readLine()!.components(separatedBy: " ").map { Int($0)! } +var N = input[0] +let K = input[1] + +// N을 2진수로 만들고 배열로 변경 Ex) 1110 -> ["1", "1", "1", "0"] +let binaryN = Array(String(N, radix: 2)) +// 배열로 만든 2진수 N을 지수만 저장 Ex) ["1", "1", "1", "0"] -> [3, 2, 1] +var array: Array = [] +for (idx, bin) in binaryN.enumerated() { + if bin == "1" { + array.append(binaryN.count - 1 - idx) + } +} + +// 만약 상점에서 더 살 필요가 없으면 0 출력 +if array.count <= K { + print(0) +} else { // K = 1 이라면 2^2 - 2^1 , K = 2 이라면 2^3 - (2^2 + 2^1) + let sum = array[K.. Int { + return 3 * r + c +} + +func from1DTo2D(_ idx: Int) -> (Int, Int) { + return (idx / 3, idx % 3) +} + +func strSwap(_ left: Int, _ right: Int, _ text: String) -> String { + var textArray = Array(text) + textArray.swapAt(left, right) + return String(textArray) +} +// MARK: - 구현 +var visited = Set() + +/// 동서남북 (1,0) (-1,0) (0,1) (0,-1) +let dr = [1, -1, 0, 0] +let dc = [0, 0, 1, -1] + +var board: [String] = [] +for _ in 0..<3 { + let line = readLine()! + board += line.components(separatedBy: " ") +} + +let zeroIdx = board.firstIndex(of: "0")! +/// initState -> (1차원배열로 바꾼 번호판, 0의1차원배열idx) +let initState = (board.joined(), zeroIdx) + +func bfs(_ startState: (String, Int)) -> Int { + var q = [(startState, 0)] + var index = 0 + visited.insert(startState.0) + + /// queue에 있는 모든 state 탐색할 때까지 + while index < q.count { + let (state, depth) = q[index] + index += 1 + + /// 완성된 번호판일 때 depth return + if state.0 == "123456780" { + return depth + } + + let (r, c) = from1DTo2D(state.1) + /// 동서남북 하나씩 모두 옮겨보고 nextState 정하는 과정 + for i in 0..<4 { + let nr = r + dr[i] + let nc = c + dc[i] + + /// 3*3 번호판 벗어날 경우 pass + if nr < 0 || nr > 2 || nc < 0 || nc > 2 { + continue + } + + let nextIdx = from2DTo1D(nr, nc) + let nextStateStr = strSwap(state.1, nextIdx, state.0) + let nextState = (nextStateStr, nextIdx) + + /// 이미 탐색한 번호판 상태이므로 pass + if visited.contains(nextState.0) { + continue + } + + /// 그 다음 depth를 탐방해야하는 nextState를 queue에 추가 + q.append((nextState, depth + 1)) + visited.insert(nextState.0) + } + } + /// queue 모두 탐색했지만, "1234567890"에 도달하지 못했을 때 + return -1 +} + +print(bfs(initState)) + + diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.2/boj_19583.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.2/boj_19583.swift new file mode 100644 index 0000000..3d84273 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.2/boj_19583.swift @@ -0,0 +1,44 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 2024/07/02. +// + +// 1. 개강총회 시작 전+ 시작하자마자 '대화'한 적 있는 닉네임 체크 +// 2. 개강총회 끝 + 스트리밍 끝날 때까지 '대화' 한 적 있는 닉네임 체크 +// 3. 스트리밍 끝나고 대화한 닉네임은 다음 스트리밍 기록으로 간주 +// 4. 대기시간은 00:00 부터 + +// 시작출석을 안하고 퇴장출석만 하는 사람도 있다는 것을 간과 + +import Foundation + +let times = readLine()! +let splitedtimes = times.components(separatedBy: " ") +let openMeetStartTime = splitedtimes[0] +let openMeetEndTime = splitedtimes[1] +let streamingEndTime = splitedtimes[2] + +var lastChatTime = "00:00" +var openAttendees: Set = [] +var endAttendees: Set = [] + +repeat { + if let chat = readLine() { + if chat.isEmpty { break } + let splitedChat = chat.components(separatedBy: " ") + let chatTime = splitedChat[0] + let studentName = splitedChat[1] + + if chatTime <= openMeetStartTime { + openAttendees.insert(studentName) + } else if chatTime >= openMeetEndTime && chatTime <= streamingEndTime { + endAttendees.insert(studentName) + } + lastChatTime = chatTime + } else { break } + +} while streamingEndTime >= lastChatTime + +print(Array(openAttendees.intersection(endAttendees)).count) diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/BinarySearchAlgorithm.md b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/BinarySearchAlgorithm.md new file mode 100644 index 0000000..764dedd --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/BinarySearchAlgorithm.md @@ -0,0 +1,47 @@ +# Binary Search Algorithm +이분탐색 알고리즘 + +## OverView +- 이분탐색 알고리즘은 정렬된 배열에서 특정 값을 찾기 위해 사용하는 알고리즘이다. +- 이 알고리즘은 배열을 반복적으로 반으로 나누면서 목표 값을 찾아가는 방식으로 동작한다. +- 이를 통해 검색 범위를 매 단계마다 절반으로 줄일 수 있으므로, 시간 복잡도가 **O(log n)**이다. + +## 장단점 +### 이분탐색의 장점 +빠른 검색 속도: 시간 복잡도가 O(log n)으로, 배열의 크기가 커져도 검색 시간이 크게 증가하지 않는다 +### 이분탐색의 단점 +정렬 필요: 배열이 정렬되어 있어야만 사용할 수 있다 + +## Swift 구현 +``` +func binarySearch(arr: [Int], target: Int) -> Int? { + // 1. 배열의 시작점(왼쪽 인덱스)과 끝점(오른쪽 인덱스)을 설정 + var left = 0 + var right = arr.count - 1 + + // 시작점이 끝점보다 커질 때까지(검색 범위가 유효할 때까지) 반복 + while left <= right { + // 2. 시작점과 끝점의 중간 인덱스를 계산 + let mid = left + (right - left) / 2 + + if arr[mid] == target { // 3-1. 만약 중간점의 값이 목표 값과 같다면, 중간 인덱스를 반환 + return mid + } else if arr[mid] < target { // 3-2. 만약 중간점의 값이 목표 값보다 작다면, 목표 값은 중간점 오른쪽에 있으므로 검색 범위를 중간점의 오른쪽 절반으로 좁힌다 + left = mid + 1 + } else { // 3-3. 만약 중간점의 값이 목표 값보다 크다면, 목표 값은 중간점 왼쪽에 있으므로 검색 범위를 중간점의 왼쪽 절반으로 좁힌다 + right = mid - 1 + } + } + + // 검색 범위가 유효하지 않게되면 목표값이 배열에 존재하지 않으므로 nil 반환 + return nil +} + +// 예제 배열 +let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +if let index = binarySearch(arr: arr, target: 7) { + print("Target found at index \(index)") +} else { + print("Target not found in the array") +} +``` diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/ParametricSearchAlgorithm.md b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/ParametricSearchAlgorithm.md new file mode 100644 index 0000000..768476b --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/ParametricSearchAlgorithm.md @@ -0,0 +1,49 @@ +# Parametric Search Algorithm +파라메트릭 서치 알고리즘 + +## OverView +파라메트릭 서치는 최적화 문제를 해결하는 알고리즘 중 하나로, 이분탐색을 활용하여 문제의 파라미터 값을 결정한다. +주로 "주어진 조건을 만족하는 최대값" 또는 "최소값"을 찾는 문제에서 사용된다. + +## 예제 +문제: 주어진 나무 높이 배열에서 총 M만큼의 나무를 가져가기 위해 절단기의 최소 높이를 찾아라 +(이 문제를 결정 문제로 변환하면, 특정 높이로 모든 나무를 잘라냈을 때, 총 M만큼의 나무를 얻을 수 있는지 여부를 판단하면 된다) + +``` +func canCutTrees(trees: [Int], height: Int, target: Int) -> Bool { + var totalWood = 0 + for tree in trees { + if tree > height { + totalWood += tree - height + } + } + return totalWood >= target +} + +func findMaxSawHeight(trees: [Int], target: Int) -> Int { + var left = 0 + var right = trees.max() ?? 0 + var result = 0 + + while left <= right { + let mid = left + (right - left) / 2 + if canCutTrees(trees: trees, height: mid, target: target) { + result = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + + return result +} + +// 예제 배열 +let trees = [20, 15, 10, 17] +let target = 7 +let maxHeight = findMaxSawHeight(trees: trees, target: target) +print("최적의 절단기 높이는 \(maxHeight)입니다.") +// maxHeight은 15가 나온다 15짜리 절단기로 나무를 자르면 [5, 0, 0, 2]가 되므로 총 target=7의 나무를 얻을 수 있다 +``` + + diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/PrefixSumAlgorithm.md b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/PrefixSumAlgorithm.md new file mode 100644 index 0000000..09c28be --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.23/7_23_Document.docc/PrefixSumAlgorithm.md @@ -0,0 +1,25 @@ +# Prefix Sum Algorithm +누적합 알고리즘 + +## OverView +누적합 알고리즘은 배열 각 요소에 대해, 그 이전 요소들까지의 합을 계산하는 알고리즘 +ex. [1, 2, 3, 4, 5] -> [1, 3(1+2), 6(1+2+3), 10, 15] + +## Swift 구현 +``` +func prefixSum(arr: [Int]) -> [Int] { + var prefixSumArr = [Int](repeating: 0, count: arr.count) + prefixSumArr[0] = arr[0] + + for i in 1.. 좀 더 봐야함 +import Foundation + +func solution(_ coin:Int, _ cards:[Int]) -> Int { + let N = cards.count + var round = 0 + var leftCoin: Int = coin + var leftCards: [Int] = Array(cards[cards.count/3..= 1 { + print("case one coin : \(mc), \(lc), \(coin)") + dfs(mc: afterMyCards1, lc: Array(lc[2..= 2 { + print("case two coin : \(mc), \(lc), \(coin)") + dfs(mc: mc, lc: Array(lc[2.. [Int]? { + if myCards.count < 2 { return nil } + var newMyCards: [Int] = myCards + for i in 0.. [Int]? { + if myCards.count < 1 { return nil } + var newMyCards: [Int] = myCards + for i in 0.. 좀 더 봐야함 +import Foundation + +func solution(_ coin:Int, _ cards:[Int]) -> Int { + let N = cards.count + var round = 0 + var leftCoin: Int = coin + var leftCards: [Int] = Array(cards[cards.count/3..= 1 { + print("case one coin : \(mc), \(lc), \(coin)") + dfs(mc: afterMyCards1, lc: Array(lc[2..= 2 { + print("case two coin : \(mc), \(lc), \(coin)") + dfs(mc: mc, lc: Array(lc[2.. [Int]? { + if myCards.count < 2 { return nil } + var newMyCards: [Int] = myCards + for i in 0.. [Int]? { + if myCards.count < 1 { return nil } + var newMyCards: [Int] = myCards + for i in 0.. Int? { + return heap.first + } + +/// 힙에 새로운 값 추가, 값 추가 후 siftUp(from: )을 호출하여 힙 정렬 + mutating func insert(_ value: Int) { + heap.append(value) + siftUp(from: heap.count - 1) + } + +/// 힙의 최상위 요소를 제거하고 반환, 최상위 요소를 제거하고, 마지막 요소를 루트로 이동시키고, siftDown(from: )을 호출하여 힙 정렬 + mutating func remove() -> Int? { + guard !heap.isEmpty else { + return nil + } + if heap.count == 1 { + return heap.removeFirst() + } else { + let value = heap[0] + heap[0] = heap.removeLast() + siftDown(from: 0) + return value + } + } + +/// 가장 하위 노드 부터 siftUp(from: )을 통해 정렬 + private mutating func siftUp(from index: Int) { + var childIndex = index + let childValue = heap[childIndex] + var parentIndex = (childIndex - 1) / 2 + + /// 부모가 자식보다 큰 경우 계속 위치 변경 + while childIndex > 0 && childValue < heap[parentIndex] { + heap[childIndex] = heap[parentIndex] + childIndex = parentIndex + parentIndex = (childIndex - 1) / 2 + } + + /// childIdx가 정해지면 추가된 값을 heap[childIndex]에 대입 + heap[childIndex] = childValue + } + +/// 가장 하위 노드를 루트로 이동 시킨 후 루트 인덱스 부터 siftDown(from: )을 통해 정렬 + private mutating func siftDown(from index: Int) { + let count = heap.count + var parentIndex = index + let parentValue = heap[parentIndex] + var childIndex = 2 * parentIndex + 1 + + /// 가장 하위 노드까지 확인 + while childIndex < count { + /// 오른쪽 자식이 왼쪽 자식보다 작다면 바꿀 자식노드를 오른쪽으로 변경 (바꿀 자식 선택) + if childIndex + 1 < count && heap[childIndex + 1] < heap[childIndex] { + childIndex += 1 + } + /// 자식이 비교 대상인 루트값보다 크거나 같다면 break + if parentValue <= heap[childIndex] { + break + } + /// 자식값 위로 올림 + heap[parentIndex] = heap[childIndex] + parentIndex = childIndex + childIndex = 2 * parentIndex + 1 + } + + /// parentIdx가 정해지면 루트에 있었던 값을 heap[parentIndex]에 대입 + heap[parentIndex] = parentValue + } +} + +``` + +### Priority Queue +Priority Queue는 우선순위가 높은 요소가 먼저 처리되는 자료구조이다. +대부분 내부적으로 힙을 사용하여 구현된다. + +## Heap & Priority Queue +|특성|Heap|Priority Queue| +|------|---|---| +|정의|완전 이진 트리|우선순위 기반 큐| +|구현 방식|배열로 구현|힙을 사용하여 구현| +|주요 연산|삽입, 삭제, 최대/최소 값|삽입, 삭제, 최고 우선순위 값| +|사용 예시|힙 정렬, 우선순위 큐 구현|작업 스케줄링, 다익스트라 알고리즘| +|복잡도|삽입 O(logn), 삭제 O(logn)|삽입 O(logn), 삭제 O(logn)| diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.9/boj_1715.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.9/boj_1715.swift new file mode 100644 index 0000000..261b660 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/7.9/boj_1715.swift @@ -0,0 +1,162 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 2024/07/04. +// + +// 무조건 적은 것부터 더해 나가는 것이 가장 적은 횟수가 될 것이다 +// 10 20 40 -> 10 + 20 + (10 + 20) + 40 -> (10 + 20) * 2 + 40 +// 짝수라면 n / 2, 홀수라면 n / 2 + 1 +// 1. 가장 작은 수 순서대로 sorting +// 2. 가장 작은 수 부터 두개씩 짝지어서 * n + + + +import Foundation + +/* 첫번째 시도 +/* 오류 -> 30 40 50 60 이 있으면, 30+40 후 (30+40) + 50 이 아닌 50 < 60 < (30+40) 이르모 50+60을 해야한다 */ +let count = Int(readLine()!)! +var array: [Int] = [] +for _ in 0 ..< count { + array.append(Int(readLine()!)!) +} +array.sort(by: <) + +var answer: Int = array[0] * (count - 1) +for i in 1 ..< count { + answer += array[i] * (count - i) +} + +print(answer) +*/ + +/* 두번째 시도 +/* 오류 -> 시간초과 */ +let count = Int(readLine()!)! +var array: [Int] = [] +for _ in 0 ..< count { + array.append(Int(readLine()!)!) +} +array.sort(by: <) + +if count == 1 { + print(0) +} else { + var answer: Int = 0 + for _ in 0 ... count / 2 { + let sum = array[0] + array[1] + answer += sum + array.removeFirst() + array.removeFirst() + array.append(sum) + array.sort(by: <) + } + print(answer) +} +*/ + +// 세번째 시도 -> 힙 직접 구현 & 0 ..< count/2이 아닌 0 ..< count-1 + +struct MinHeap { + private var heap = [Int]() + + var isEmpty: Bool { + return heap.isEmpty + } + + var count: Int { + return heap.count + } + +/// 힙의 최상위 요소를 반환 (여기서는 최소값), 비어있으면 nil + func peek() -> Int? { + return heap.first + } + +/// 힙에 새로운 값 추가, 값 추가 후 siftUp(from: )을 호출하여 힙 정렬 + mutating func insert(_ value: Int) { + heap.append(value) + siftUp(from: heap.count - 1) + } + +/// 힙의 최상위 요소를 제거하고 반환, 최상위 요소를 제거하고, 마지막 요소를 루트로 이동시키고, siftDown(from: )을 호출하여 힙 정렬 + mutating func remove() -> Int? { + guard !heap.isEmpty else { + return nil + } + if heap.count == 1 { + return heap.removeFirst() + } else { + let value = heap[0] + heap[0] = heap.removeLast() + siftDown(from: 0) + return value + } + } + +/// 가장 하위 노드 부터 siftUp(from: )을 통해 정렬 + private mutating func siftUp(from index: Int) { + var childIndex = index + let childValue = heap[childIndex] + var parentIndex = (childIndex - 1) / 2 + + /// 부모가 자식보다 큰 경우 계속 위치 변경 + while childIndex > 0 && childValue < heap[parentIndex] { + heap[childIndex] = heap[parentIndex] + childIndex = parentIndex + parentIndex = (childIndex - 1) / 2 + } + + /// childIdx가 정해지면 추가된 값을 heap[childIndex]에 대입 + heap[childIndex] = childValue + } + +/// 가장 하위 노드를 루트로 이동 시킨 후 루트 인덱스 부터 siftDown(from: )을 통해 정렬 + private mutating func siftDown(from index: Int) { + let count = heap.count + var parentIndex = index + let parentValue = heap[parentIndex] + var childIndex = 2 * parentIndex + 1 + + /// 가장 하위 노드까지 확인 + while childIndex < count { + /// 오른쪽 자식이 왼쪽 자식보다 작다면 바꿀 자식노드를 오른쪽으로 변경 (바꿀 자식 선택) + if childIndex + 1 < count && heap[childIndex + 1] < heap[childIndex] { + childIndex += 1 + } + /// 자식이 비교 대상인 루트값보다 크거나 같다면 break + if parentValue <= heap[childIndex] { + break + } + /// 자식값 위로 올림 + heap[parentIndex] = heap[childIndex] + parentIndex = childIndex + childIndex = 2 * parentIndex + 1 + } + + /// parentIdx가 정해지면 루트에 있었던 값을 heap[parentIndex]에 대입 + heap[parentIndex] = parentValue + } +} + +let count = Int(readLine()!)! +var heap = MinHeap() +for _ in 0 ..< count { + heap.insert(Int(readLine()!)!) +} + +if count == 1 { + print(0) +} else { + var answer: Int = 0 + for _ in 0 ..< count-1 { + let num1 = heap.remove()! + let num2 = heap.remove()! + let sum = num1 + num2 + answer += sum + heap.insert(sum) + } + print(answer) +} diff --git "a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.13/programmers_\354\236\205\352\265\255\354\213\254\354\202\254.swift" "b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.13/programmers_\354\236\205\352\265\255\354\213\254\354\202\254.swift" new file mode 100644 index 0000000..f6a4a34 --- /dev/null +++ "b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.13/programmers_\354\236\205\352\265\255\354\213\254\354\202\254.swift" @@ -0,0 +1,39 @@ +// +// programmers_입국심사.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 8/13/24. +// + +import Foundation + +func solution(_ n:Int, _ times:[Int]) -> Int64 { // n = 6, times = [7, 10] + guard let max = times.max() else { return 0 } + + var start = 1 + var end = max * n // 60 + + while start < end { + var mid = (start + end) / 2 // [1]: 30분, [2]: 15분, [3]: (16+30)/2 = 23, [4]: (24+30)/2 = 27, [5]: (28+30)/2 = 29, [6]: (28+29)/2 = 28 + var acceptableCnt: Int = 0 + times.forEach { time in + acceptableCnt += mid / time + // [1] 30분 동안 수용 최대 인원 구하기 -> 7분 걸리는 심사원은 4명을, 10분 걸리는 심사원은 3명 수용 총 7명 (가능) + // [2] 15분 동안 수용 최대 인원 구하기 -> 7분 걸리는 심사원은 2명을, 10분 걸리는 심사원은 1명 수용 총 3명 (불가능) + // [3] 23분 동안 수용 최대 인원 구하기 -> 7분 걸리는 심사원은 3명을, 10분 걸리는 심사원은 2명 수용 총 5명 (불가능) + // [4] 27분 동안 수용 최대 인원 구하기 -> 7분 걸리는 심사원은 3명을, 10분 걸리는 심사원은 2명 수용 총 5명 (불가능) + // [5] 29분 동안 수용 최대 인원 구하기 -> 7분 걸리는 심사원은 4명을, 10분 걸리는 심사원은 2명 수용 총 6명 (가능) -> 아직 start 7분 걸리는 심사원은 4명을, 10분 걸리는 심사원은 2명 수용 총 6명 (가능) + } + + if acceptableCnt >= n { // 가능 -> 시간이 남는다는 뜻 -> 앞쪽을 탐색 + end = mid // [6]에서 end=29를 end=28로 변경하면 start=28과 같아지게 되므로 다음 while문 통과안하고 종료 + } else { // 불가능 -> 시간이 부족하다는 뜻 -> 뒷쪽을 탐색 + start = mid + 1 + } + } + + return Int64(start) +} + +print(solution(6, [7,10])) diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.20/boj_2839.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.20/boj_2839.swift new file mode 100644 index 0000000..156b5f9 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.20/boj_2839.swift @@ -0,0 +1,28 @@ +// +// boj_2839.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 8/20/24. +// + +import Foundation + +var num = Int(readLine()!)! +var count = 0 + +while true { + if num % 5 == 0 { + print(num/5 + count) + break + } else { + num -= 3 + count += 1 + if num == 0 { + print(count) + break + } else if num < 0 { + print(-1) + break + } + } +} diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_1149.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_1149.swift new file mode 100644 index 0000000..d6038d2 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_1149.swift @@ -0,0 +1,33 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 8/26/24. +// + +import Foundation + +let houseCnt: Int = Int(readLine()!)! +var RGB: [[Int]] = [[0,0,0]] +for _ in 1 ... houseCnt { + let rgb = readLine()!.components(separatedBy: " ").map { Int($0)! } + RGB.append(rgb) +} + +var dp = [(sum: Int, last: Int)].init(repeating: (0,0), count: houseCnt + 1) +for i in 1 ... houseCnt { + if i == 1 { + let min = RGB[i].min()! + dp[i] = (min, RGB[i].firstIndex(of: min)!) + } else { + var rgb = RGB[i] + _ = rgb.remove(at: dp[i-1].last) + let min = rgb.min()! + print(rgb, dp[i-1].last, min) + dp[i] = (min + dp[i-1].sum, RGB[i].firstIndex(of: min)!) + } +} + +print(dp[houseCnt].sum) + +// 예제3, 5 통과 못함 diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_11727.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_11727.swift new file mode 100644 index 0000000..ecf7daa --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_11727.swift @@ -0,0 +1,26 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 8/25/24. +// + +// 2×n 직사각형을 1×2, 2×1과 2×2 타일로 채우는 방법의 수를 구하는 프로그램을 작성하시오. + +import Foundation + +let n = Int(readLine()!)! +var dp: [Int] = Array(repeating: 0, count: n+1) + +if n == 1 { + print(1) +} else if n == 2 { + print(3) +} else { + dp[1] = 1 + dp[2] = 3 + for i in 3...n { + dp[i] = (dp[i-1] + 2*dp[i-2]) % 10007 + } + print(dp[n]) +} diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_2156.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_2156.swift new file mode 100644 index 0000000..3f55206 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.27/boj_2156.swift @@ -0,0 +1,64 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 8/26/24. +// + +import Foundation + +var glasses: [Int] = [0] +let glassCnt: Int = Int(readLine()!)! +for _ in 1 ... glassCnt { + glasses.append(Int(readLine()!)!) +} + +// - 두번째 시도 +var dp: [Int] = Array(repeating: 0, count: glassCnt + 1) +for i in 1 ... glassCnt { + if i == 1 { + dp[i] = glasses[i] + } else if i == 2 { + dp[i] = glasses[i-1] + glasses[i] + } else { + // 4개라고 가정할 때, (1+2+new), (1+3+new), 제일 최근 max (연달아 세개가 될 경우) 중 max + dp[i] = max(dp[i-2] + glasses[i], dp[i-3] + glasses[i-1] + glasses[i], dp[i-1]) + } +} + +print(dp[glassCnt]) + +// - 첫번째 시도 + +//var dp: [[Int]] = Array(repeating: [], count: glassCnt + 1) +//for glassIdx in 1 ... glassCnt { +// if glassIdx == 1 { +// dp[1] = [0] +// } else if glassIdx == 2 { +// dp[2] = [0,1] +// } else { +// dp[glassIdx] = makeMax(prevMaxArr: dp[glassIdx-1], newIdx: glassIdx-1) +// } +// +//} +//print(dp[glassCnt].reduce(0, { $0 + glasses[$1] })) +// +//func makeMax(prevMaxArr: [Int], newIdx: Int) -> [Int] { +// var newMaxArr: [Int] = prevMaxArr +// +// if prevMaxArr[prevMaxArr.count - 2] + 1 == prevMaxArr[prevMaxArr.count - 1] && +// prevMaxArr[prevMaxArr.count - 1] + 1 == newIdx { +// let prevMax = prevMaxArr.max(by: { glasses[$0] < glasses[$1] })! +// let prevMin = prevMaxArr.min(by: { glasses[$0] < glasses[$1] })! +// let prevMaxSum = prevMaxArr.reduce(0, { $0 + glasses[$1] }) +// +// if glasses[prevMax] + glasses[newIdx] > prevMaxSum { +// newMaxArr.remove(at: prevMin) +// newMaxArr.append(newIdx) +// } +// } else { +// newMaxArr.append(newIdx) +// } +// +// return newMaxArr +//} diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.3/boj_17825.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.3/boj_17825.swift new file mode 100644 index 0000000..1094312 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.3/boj_17825.swift @@ -0,0 +1,112 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 8/5/24. +// + +import Foundation + +typealias Meeple = (boardIdx: Int, positionIdx: Int) + +let moves = readLine()!.components(separatedBy: " ").map { Int($0)! } +// 탐색 공간 +// 25, 30, 35, 40이 각각 보드에 다 존재하면 안됨 (중복 체크 못함) +// through10, **20, **30 모두 첫자리를 비워둬야함 (0으로 비워둠) + +let straightBoard: [Int] = Array(stride(from: 0, to: 40, by: 2)) +let through10Board: [Int] = [10, 13, 16, 19] +let through20Board:[Int] = [20, 22, 24] +let through30Board: [Int] = [30, 28, 27, 26] +let lastCommonBoard: [Int] = [25, 30, 35, 40, 0] +let board: [[Int]] = [straightBoard, through10Board, through20Board, through30Board, lastCommonBoard] + +var meeples = [Meeple].init(repeating: Meeple(0,0), count: 4) + +var maxScore: Int = 0 + +func moveMeeple(_ meeple: Meeple, for move: Int) -> Meeple { + let curBoard = board[meeple.boardIdx] + + if curBoard == straightBoard { // 1. 현재 꺾는 곳 없이 가장 크게 한바퀴를 돌고 있는 경우 + let movedIdx = meeple.positionIdx + move + + if movedIdx > 20 { // movedIdx가 20을 초과한 경우, 보드판을 벗어나 lastCommonBoard의 마지막인덱스로 + return (4, 4) + + } else if movedIdx == 20 { + return (4, 3) + } else { + let movedScore = straightBoard[movedIdx] + if movedScore == 10 { // 10에서 멈춘경우, through10Board의 첫번째로 변경 + return (1, 0) + } else if movedScore == 20 { // 20에서 멈춘경우, through10Board의 첫번째로 변경 + return (2, 0) + } else if movedScore == 30 { // 30에서 멈춘경우, through10Board의 첫번째로 변경 + return (3, 0) + } else { // 위 해당사항에 포함되지 않으면 straightBoard에서 쭉 이동 + return (0, movedIdx) + } + } + + } else if curBoard == through10Board { // 2. [0, 13, 16, 19] + let movedIdx = meeple.positionIdx + move + if movedIdx > 3 { // through10Board를 벗어나면 lastCommonBoard로 이동 + return (4, movedIdx - through10Board.count) + } else { + return (1, movedIdx) + } + + } else if curBoard == through20Board { // 3. [0, 22, 24] + let movedIdx = meeple.positionIdx + move + if movedIdx > 2 { // through10Board를 벗어나면 lastCommonBoard로 이동 + return (4, movedIdx - through20Board.count) + } else { + return (2, movedIdx) + } + + } else if curBoard == through30Board { // 4. [0, 28, 27, 26] + let movedIdx = meeple.positionIdx + move + if movedIdx > 3 { // through10Board를 벗어나면 lastCommonBoard로 이동 + return (4, movedIdx - through30Board.count) + } else { + return (3, movedIdx) + } + + } else { // 5. curBoard == lastCommonBoard -> [25, 30, 35, 40, 0] + let movedIdx = min(meeple.positionIdx + move, 4) + return (4, movedIdx) + } +} + +func play(_ turn: Int, _ score: Int) { + guard turn < 10 else { + if maxScore < score { maxScore = score } + return + } + + for movingIdx in 0..<4 where meeples[movingIdx] != (4, 4) { + let meeple = meeples[movingIdx] + + let movedMeeple = moveMeeple(meeple, for: moves[turn]) + // 놓여져 있는 말과 동일한 위치에 있을 수 없으므로 비교를 한다 + // 조건1. 이미 완주한 말은 비교대상에서 제외 + // 조건2. 현재 이동중인 말 비교대상에서 제외 + var canMove = true + for compareIdx in 0..<4 where meeples[compareIdx] != (4, 4) && compareIdx != movingIdx { + if meeples[compareIdx] == movedMeeple { // 이미 이동하고자 하는 위치에 다른 말이 있다면 + canMove = false + break + } + } + + if canMove { + meeples[movingIdx] = movedMeeple + play(turn + 1, score + board[movedMeeple.boardIdx][movedMeeple.positionIdx]) + meeples[movingIdx] = meeple + } + } +} + +play(0,0) +print(maxScore) diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.3/boj_2352.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.3/boj_2352.swift new file mode 100644 index 0000000..a8e8f04 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/8.3/boj_2352.swift @@ -0,0 +1,38 @@ +// +// main.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 8/5/24. +// + +// 문제 유형 파악에 시간 소모 +import Foundation + +let _ = Int(readLine()!)! +var list = readLine()!.split(separator: " ").map{ Int(String($0))! } +var lisList: [Int] = [list[0]] + +for i in 1.. Int { + if num != parent[num] { + parent[num] = find(parent[num]) + } + return parent[num] +} + +func unionFind(x: Int, y: Int) { + let rootX = find(x) + let rootY = find(y) + if rootX != rootY { + if rootX < rootY { + parent[rootY] = rootX + } else { + parent[rootX] = rootY + } + } +} + +// [0, 1, 2, 1, 4, 2, 2, 7, 7, 4, 2] +for _ in 0 ..< M { + let r = readLine()!.components(separatedBy: " ").map { Int($0)! } + unionFind(x: r[0], y: r[1]) +} + +for i in 0 ... N { + if i != parent[i] { + friends[find(i)] += 1 + candies[find(i)] += candies[i] + // root가 되는 친구의 index에 그룹 내의 친구 수, 사탕 수가 저장될 것 + } +} + +parent = Array(Set(parent).subtracting([0])) +// 아이들을 다 돌 필요 없이 우두머리 친구를 통해 그룹 통째로 확인하면 됨 +var dp: [[Int]] = [[Int]](repeating: [Int](repeating: 0, count: K+1), count: parent.count) +for i in 0 ..< parent.count { + let rep = parent[i] + for j in 1 ... K { + if i == 0 { + dp[i][j] = friends[rep] <= j ? candies[rep] : 0 + } else { + if friends[rep] <= j { // 그룹 다 뺏어도 들키지 않는 범위 내일 때 + dp[i][j] = max(dp[i-1][j], dp[i-1][j-friends[rep]] + candies[rep]) + } else { // 이 그룹의 사탕을 뺏을 경우 K를 넘어갈 때 + dp[i][j] = dp[i-1][j] + } + } + } +} + +print(dp.last![K-1]) diff --git a/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/9.3/boj_12865.swift b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/9.3/boj_12865.swift new file mode 100644 index 0000000..a589c19 --- /dev/null +++ b/jihyeon/AlgorithmStudyS8JH/AlgorithmStudyS8JH/9.3/boj_12865.swift @@ -0,0 +1,40 @@ +// +// boj_12865.swift +// AlgorithmStudyS8JH +// +// Created by 김지현 on 9/3/24. +// + +import Foundation + +let firstLine = readLine()!.components(separatedBy: " ").map { Int($0)! } +var N: Int = firstLine[0] // (1 <= N(물품의 수) <= 100) +var K: Int = firstLine[1] // (1 <= K(버틸 수 있는 총 무게) <= 100,000) + +var objects: [(W: Int, V: Int)] = [] +for i in 0 ..< N { + let object = readLine()!.components(separatedBy: " ").map { Int($0)! } + objects.append((object[0], object[1])) +} + +var dp: [[Int]] = [[Int]](repeating: [Int](repeating: 0, count: K+1), count: N) + +for i in 0..= objects[i].W { + dp[i][j] = objects[i].V + } + } else { + if objects[i].W <= j { // W <= K + dp[i][j] = max(dp[i-1][j], dp[i-1][j-objects[i].W] + objects[i].V) + } else { // W > K + dp[i][j] = dp[i-1][j] + } + } + + } +} + +print(dp[N-1][K]) diff --git a/temp/reporepo/.cph/.main.cpp_323487e934c404d0d38028ae77afa265.prob b/temp/reporepo/.cph/.main.cpp_323487e934c404d0d38028ae77afa265.prob new file mode 100644 index 0000000..171880e --- /dev/null +++ b/temp/reporepo/.cph/.main.cpp_323487e934c404d0d38028ae77afa265.prob @@ -0,0 +1 @@ +{"name":"Local: main","url":"c:\\Users\\hge42\\Desktop\\ghan\\univ\\cote\\reporepo\\main.cpp","tests":[{"id":1710823587613,"input":"","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"c:\\Users\\hge42\\Desktop\\ghan\\univ\\cote\\reporepo\\main.cpp","group":"local","local":true} \ No newline at end of file diff --git a/temp/reporepo/.cph/.repair_hangseung.cpp_d96e4caf6a7d875abdee285226d7ca28.prob b/temp/reporepo/.cph/.repair_hangseung.cpp_d96e4caf6a7d875abdee285226d7ca28.prob new file mode 100644 index 0000000..c385fee --- /dev/null +++ b/temp/reporepo/.cph/.repair_hangseung.cpp_d96e4caf6a7d875abdee285226d7ca28.prob @@ -0,0 +1 @@ +{"name":"Local: repair_hangseung","url":"c:\\Users\\hge42\\Desktop\\ghan\\univ\\cote\\reporepo\\repair_hangseung.cpp","tests":[{"id":1710829253104,"input":"","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"c:\\Users\\hge42\\Desktop\\ghan\\univ\\cote\\reporepo\\repair_hangseung.cpp","group":"local","local":true} \ No newline at end of file diff --git "a/temp/reporepo/.cph/.\354\210\230\353\246\254\352\263\265_\355\225\255\354\212\271.cpp_d32c986dff71b83210b66ba47b5d60ba.prob" "b/temp/reporepo/.cph/.\354\210\230\353\246\254\352\263\265_\355\225\255\354\212\271.cpp_d32c986dff71b83210b66ba47b5d60ba.prob" new file mode 100644 index 0000000..81a7330 --- /dev/null +++ "b/temp/reporepo/.cph/.\354\210\230\353\246\254\352\263\265_\355\225\255\354\212\271.cpp_d32c986dff71b83210b66ba47b5d60ba.prob" @@ -0,0 +1 @@ +{"name":"수리공 항승","group":"Baekjoon Online Judge","url":"https://www.acmicpc.net/problem/1449","interactive":false,"memoryLimit":128,"timeLimit":2000,"tests":[{"input":"4 2\n1 2 100 101\n","output":"2\n","id":1710823629488},{"input":"4 3\n1 2 3 4\n","output":"2\n","id":1710823629527},{"id":1710823629483,"input":"3 1\n3 2 1","output":"3"}],"testType":"single","input":{"type":"stdin"},"output":{"type":"stdout"},"languages":{"java":{"mainClass":"Main","taskClass":"Task"}},"batch":{"id":"c096bf03-ec8f-4330-9354-58bd099dfc3e","size":1},"srcPath":"c:\\Users\\hge42\\Desktop\\ghan\\univ\\cote\\reporepo\\수리공_항승.cpp"} \ No newline at end of file diff --git a/temp/reporepo/.gitignore b/temp/reporepo/.gitignore new file mode 100644 index 0000000..6d2922f --- /dev/null +++ b/temp/reporepo/.gitignore @@ -0,0 +1 @@ +**./*.exe \ No newline at end of file diff --git a/temp/reporepo/.vscode/c_cpp_properties.json b/temp/reporepo/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..6e97c77 --- /dev/null +++ b/temp/reporepo/.vscode/c_cpp_properties.json @@ -0,0 +1,17 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "compilerPath": "C:/msys64/ucrt64/bin/g++.exe" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/temp/reporepo/.vscode/settings.json b/temp/reporepo/.vscode/settings.json new file mode 100644 index 0000000..0cba2e6 --- /dev/null +++ b/temp/reporepo/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "iostream": "cpp" + } +} \ No newline at end of file diff --git a/temp/reporepo/.vscode/tasks.json b/temp/reporepo/.vscode/tasks.json new file mode 100644 index 0000000..8d70cdf --- /dev/null +++ b/temp/reporepo/.vscode/tasks.json @@ -0,0 +1,28 @@ +{ + "tasks": [ + { + "type": "cppbuild", + "label": "C/C++: g++.exe build active file", + "command": "C:\\msys64\\ucrt64\\bin\\g++.exe", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "C:\\msys64\\ucrt64\\bin" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "detail": "Task generated by Debugger." + } + ], + "version": "2.0.0" +} \ No newline at end of file diff --git a/temp/reporepo/01_variable_type.cpp b/temp/reporepo/01_variable_type.cpp new file mode 100644 index 0000000..0c0d1a5 --- /dev/null +++ b/temp/reporepo/01_variable_type.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; + +int main(){ + ////////////////////////////////////////////////////number////////////////////////////////////////////////////////// + cout << "" << endl; + int i = 123; + // i라는 변수를 만들었다면, 동일한 scope에서 같은 이름의 변수 생성 불가능. e.g. i = 456으로 새로운 값 넣어주는 건 가능, int i = 456;으로 같은 이름의 변수 생성은 불가능. + cout << i << " " << sizeof(i) << endl; // 4 Byte + // c와 cpp는 메모리에 직접 변수를 저장하는 방식, 파이썬은 객체 레퍼런스 방식 -> 그래서 파이썬이 느리다는겨 + + float num1 = 123.7; // c++에선 사실 소숫점을 포함한 실수는 모두 double임. 여기서는 double이 float형 변수에 저장되게 됨으로써, 사실상 casting이 발생한 것. + float num2 = 123.7f; + double num3 = 123.7; + cout<< "size of num1: " << sizeof(num1) << endl << + "size of num2: " << sizeof(num2) << endl << + "size of num3: " << sizeof(num3) << endl; + + ////////////////////////////////////////////////////string////////////////////////////////////////////////////////// + cout << endl << "" << endl; + // 글자 하나와 문자열의 구분 + char c = 'a'; + char str[] = "Hello, world!"; //배열 선언 시, 초기값을 지정해주는 경우 알아서 배열 크기 조정해줘. 근데 std에 String형 있음 + cout << c << endl; + cout << str << endl; + cout<< "size of num1: " << sizeof(c) << endl << + "size of num2: " << sizeof(str) << endl; //마지막 null char(\0)으로 총 14글자 + + ////////////////////////////////////////////////////boolean////////////////////////////////////////////////////////// + cout << endl << "" << endl; + bool is_good = true; + + cout << is_good << endl; + cout << !is_good << endl; + cout << (is_good & 00) << endl; + // boolalpha & noboolalpha 옵션으로 'true, false'로 출력할건지, '1,0'으로 출력할건지 지정. + cout << boolalpha << is_good << endl; + cout << (is_good | 0) << endl; // 이런 연산엔 boolalpha 옵션 적용 안되나봐 + cout << noboolalpha << is_good << endl; + cout << boolalpha << !is_good << endl; + + cout << "(00 & 01) = " << (00 & 01) << endl; + cout << "(01 & 01) = " << (01 & 01) << endl; + cout << "(10 & 10) = " << (10 & 10) << endl; + cout << "(11 & 11) = " << (11 & 11) << endl; + cout << noboolalpha << "(00 && 01) = " << (00 && 01) << endl; + cout << boolalpha << "(00 && 01) = " << (00 && 01) << endl; + + ///////////////////////////////////////////////////array////////////////////////////////////////////////////////// + cout << endl << "" << endl; + int my_arr[3] = {1,2,3}; // 배열 크기 설정해주는거 까먹지 마셔 + cout << "my_arr[0]: " << my_arr[0] << endl; // index is started from 0 + cout << "sizeof(my_arr): " << sizeof(my_arr) << endl; // int 3개 -> 4*3 = 12byte + + //c++에서 문자열은 문자의 배열 + char strArr[20] = "gagagagagagagagaga"; + cout << str << endl; + str[2] = '\0'; + cout << str << endl; // cout의 동작은, '\0'을 만나면 모두 출력했다고 판단. null 문자가 코테에서 중요하니 잘 기억해두자. + + + +} \ No newline at end of file diff --git a/temp/reporepo/02_stream.cpp b/temp/reporepo/02_stream.cpp new file mode 100644 index 0000000..9940952 --- /dev/null +++ b/temp/reporepo/02_stream.cpp @@ -0,0 +1,8 @@ +#include +using namespace std; + +int main(){ + // git test + cout<<"i'm pissed off.."< +using namespace std; + +int main(){ + cout<<"hello world!"< +#include +using namespace std; + +int main(){ + int leakNum; + int tapeLen; + + // get the number of leak point and the length of tape + cin >> leakNum >> tapeLen; + // if there is no leak point, terminate + if(leakNum == 0){ + cout << 0; + return 0; + } + + // get the locations of leak point + int* leakLocation = new int[leakNum]; + for(int i=0; i> *(leakLocation + i); + } + + // sort input in ascending order + sort(leakLocation, leakLocation + leakNum); + + // calc the number of tape needed + int maxDist = tapeLen - 1; + int pointer = *leakLocation; + int idx = 0; + int i=0; + int d; + int tapeNum = 1; + while(i + idx < leakNum){ + d = *(leakLocation + i + idx) - pointer; + if(d > maxDist){ + pointer = *(leakLocation + i + idx); + idx = i + idx; + tapeNum ++; + i = 1; + } + else i++; + } + cout << tapeNum; + delete[] leakLocation; +} \ No newline at end of file diff --git a/repair_hangseung.exe b/temp/reporepo/repair_hangseung.exe similarity index 100% rename from repair_hangseung.exe rename to temp/reporepo/repair_hangseung.exe diff --git "a/\352\260\200\354\235\200/helloworld.txt" "b/\352\260\200\354\235\200/helloworld.txt" deleted file mode 100644 index bc7774a..0000000 --- "a/\352\260\200\354\235\200/helloworld.txt" +++ /dev/null @@ -1 +0,0 @@ -hello world! \ No newline at end of file diff --git "a/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/1449_\354\210\230\353\246\254\352\263\265\355\225\255\354\212\271.py" "b/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/1449_\354\210\230\353\246\254\352\263\265\355\225\255\354\212\271.py" new file mode 100644 index 0000000..8f35dae --- /dev/null +++ "b/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/1449_\354\210\230\353\246\254\352\263\265\355\225\255\354\212\271.py" @@ -0,0 +1,17 @@ +import sys +input = sys.stdin.readline + +N, L = map(int, input().split()) +leaks = list(map(int, input().split())) +leaks.sort() + +is_fixed = {leak: False for leak in leaks} +answer = 0 + +for leak in leaks: + if not is_fixed[leak]: + answer += 1 + for i in range(1, L): + if leak + i in is_fixed.keys(): + is_fixed[leak + i] = True +print(answer) diff --git "a/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/1541_\354\236\203\354\226\264\353\262\204\353\246\260\352\264\204\355\230\270.py" "b/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/1541_\354\236\203\354\226\264\353\262\204\353\246\260\352\264\204\355\230\270.py" new file mode 100644 index 0000000..9abf0e0 --- /dev/null +++ "b/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/1541_\354\236\203\354\226\264\353\262\204\353\246\260\352\264\204\355\230\270.py" @@ -0,0 +1,14 @@ +import sys +input = sys.stdin.readline + +question = input().rstrip() + + +def get_sum(text): + return sum(map(int, text.split("+"))) + + +add_values = sum(map(int, question.split("-")[0].split("+"))) +subtract_values = sum(map(get_sum, question.split("-")[1:])) + +print(add_values - subtract_values) diff --git "a/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/18310_\354\225\210\355\205\214\353\202\230.py" "b/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/18310_\354\225\210\355\205\214\353\202\230.py" new file mode 100644 index 0000000..73089a7 --- /dev/null +++ "b/\354\235\230\354\247\204/1\354\243\274\354\260\250_\352\267\270\353\246\254\353\224\224/18310_\354\225\210\355\205\214\353\202\230.py" @@ -0,0 +1,8 @@ +import sys +input = sys.stdin.readline + +N = int(input()) +locations = list(map(int, input().split())) + +locations.sort() +print(locations[(len(locations)-1) // 2]) diff --git "a/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/1525_\355\215\274\354\246\220.py" "b/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/1525_\355\215\274\354\246\220.py" new file mode 100644 index 0000000..32ade73 --- /dev/null +++ "b/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/1525_\355\215\274\354\246\220.py" @@ -0,0 +1,66 @@ +import sys +from collections import deque +input = sys.stdin.readline + +visited = set() + + +def from_2d_to_1d(r, c): + return 3 * r + c + + +def from_1d_to_2d(idx): + return (idx // 3, idx % 3) + + +def str_swap(left, right, text): + text = list(text) + text[left], text[right] = text[right], text[left] + text = "".join(text) + return text + + +dr = [1, -1, 0, 0] +dc = [0, 0, 1, -1] + +board = [] + +for _ in range(3): + board += list(input().rstrip().split()) + +zero_idx = board.index("0") +init_state = ("".join(board), zero_idx) + + +def bfs(start_state): + q = deque() + q.append((start_state, 0)) + visited.add(start_state) + + while q: + state, depth = q.popleft() + if state[0] == "123456780": + return depth + + r, c = from_1d_to_2d(state[1]) + for i in range(4): + nr = r + dr[i] + nc = c + dc[i] + + if nr < 0 or nr > 2 or nc < 0 or nc > 2: + continue + + next_idx = from_2d_to_1d(nr, nc) + next_state_str = str_swap(state[1], next_idx, state[0]) + + next_state = (next_state_str, next_idx) + + if next_state in visited: + continue + + q.append((next_state, depth + 1)) + visited.add(next_state) + return -1 + + +print(bfs(init_state)) diff --git "a/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/19583_\354\213\270\354\235\264\353\262\204\352\260\234\352\260\225\354\264\235\355\232\214.py" "b/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/19583_\354\213\270\354\235\264\353\262\204\352\260\234\352\260\225\354\264\235\355\232\214.py" new file mode 100644 index 0000000..65e7764 --- /dev/null +++ "b/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/19583_\354\213\270\354\235\264\353\262\204\352\260\234\352\260\225\354\264\235\355\232\214.py" @@ -0,0 +1,40 @@ +# Set (value가 없는 Hashtable) 이용 -> 160ms +import sys +input = sys.stdin.readline + + +def time_to_regular_form(time: str): + hour, minute = map(int, time.split(":")) + regular_form = hour * 60 + minute + return regular_form + + +def log_line_to_info(log_line: str): + time, name = log_line.split() + time = time_to_regular_form(time) + return time, name + + +infos = list(input().rstrip().split()) +S = time_to_regular_form(infos[0]) +E = time_to_regular_form(infos[1]) +Q = time_to_regular_form(infos[2]) + +# print(S, E, Q) + +ans = 0 +enter_check = set() +while True: + try: + log_line = input().rstrip() + time, name = log_line_to_info(log_line) + if time <= S: + enter_check.add(name) + elif (E <= time <= Q) and (name in enter_check): + ans += 1 + enter_check.remove(name) + + except: + break + +print(ans) diff --git "a/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/19583_\354\213\270\354\235\264\353\262\204\352\260\234\352\260\225\354\264\235\355\232\214_list.py" "b/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/19583_\354\213\270\354\235\264\353\262\204\352\260\234\352\260\225\354\264\235\355\232\214_list.py" new file mode 100644 index 0000000..8fabec4 --- /dev/null +++ "b/\354\235\230\354\247\204/240702_bfsdfs_\352\265\254\355\230\204/19583_\354\213\270\354\235\264\353\262\204\352\260\234\352\260\225\354\264\235\355\232\214_list.py" @@ -0,0 +1,44 @@ +# List 이용 : Time Out +import sys +input = sys.stdin.readline + + +def time_to_regular_form(time: str): + hour, minute = map(int, time.split(":")) + regular_form = hour * 60 + minute + return regular_form + + +def log_line_to_info(log_line: str): + time, name = log_line.split() + time = time_to_regular_form(time) + return time, name + + +infos = list(input().rstrip().split()) +S = time_to_regular_form(infos[0]) +E = time_to_regular_form(infos[1]) +Q = time_to_regular_form(infos[2]) + +# print(S, E, Q) + +ans = 0 +enter_check = [] +while True: + try: + log_line = input().rstrip() + time, name = log_line_to_info(log_line) + if time <= S: + if name not in enter_check: + enter_check.append(name) + elif (E <= time <= Q): + for idx, n in enumerate(enter_check): + if n == name: + del enter_check[idx] + ans += 1 + break + + except: + break + +print(ans) diff --git "a/\354\235\230\354\247\204/240709_\355\236\231_bfsdfs_\352\265\254\355\230\204/1715_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.py" "b/\354\235\230\354\247\204/240709_\355\236\231_bfsdfs_\352\265\254\355\230\204/1715_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.py" new file mode 100644 index 0000000..d590ce0 --- /dev/null +++ "b/\354\235\230\354\247\204/240709_\355\236\231_bfsdfs_\352\265\254\355\230\204/1715_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.py" @@ -0,0 +1,24 @@ +import heapq +import sys + +input = sys.stdin.readline + +N = int(input()) +num_list = [int(input()) for _ in range(N)] + +if N == 1: + print(0) + sys.exit() + +heapq.heapify(num_list) + +ans = 0 + +while len(num_list) > 1: + first_card = heapq.heappop(num_list) + second_card = heapq.heappop(num_list) + grouped = first_card + second_card + ans += grouped + heapq.heappush(num_list, grouped) + +print(ans) diff --git "a/\354\235\230\354\247\204/240709_\355\236\231_bfsdfs_\352\265\254\355\230\204/5427_\353\266\210.py" "b/\354\235\230\354\247\204/240709_\355\236\231_bfsdfs_\352\265\254\355\230\204/5427_\353\266\210.py" new file mode 100644 index 0000000..620f6b7 --- /dev/null +++ "b/\354\235\230\354\247\204/240709_\355\236\231_bfsdfs_\352\265\254\355\230\204/5427_\353\266\210.py" @@ -0,0 +1,69 @@ +import sys +from collections import deque +from pprint import pprint +input = sys.stdin.readline + +T = int(input()) + +dr = [-1, 1, 0, 0] +dc = [0, 0, -1, 1] + + +def bfs(start, fire_pos, visited): + q = deque() + visited[start[0]][start[1]] = True + q.append((start, 0)) + cur_depth = -1 + + while q: + pos, depth = q.popleft() + r = pos[0] + c = pos[1] + + if cur_depth < depth: + cur_depth = depth + new_fire_pos = [] + for fire in fire_pos: + for i in range(4): + nr = fire[0] + dr[i] + nc = fire[1] + dc[i] + if nr < 0 or nr == h or nc < 0 or nc == w: + continue + if board[nr][nc] == ".": + board[nr][nc] = "*" + new_fire_pos.append((nr, nc)) + + fire_pos = new_fire_pos + + for i in range(4): + nr = r + dr[i] + nc = c + dc[i] + if nr < 0 or nr == h or nc < 0 or nc == w: + return depth + 1 + if board[nr][nc] != ".": + continue + if visited[nr][nc] == True: + continue + + visited[nr][nc] = True + q.append(((nr, nc), depth + 1)) + + return "IMPOSSIBLE" + + +for _ in range(T): + w, h = map(int, input().split()) + board = [list(input().strip()) for _ in range(h)] + visited = [[False] * w for _ in range(h)] + + fire_pos = [] + + for r in range(h): + for c in range(w): + if board[r][c] == "@": + start = (r, c) + board[r][c] = "." + elif board[r][c] == "*": + fire_pos.append((r, c)) + + print(bfs(start, fire_pos, visited)) diff --git "a/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/12764_\354\213\270\354\247\200\353\260\251\354\227\220\352\260\204\354\244\200\355\225\230.py" "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/12764_\354\213\270\354\247\200\353\260\251\354\227\220\352\260\204\354\244\200\355\225\230.py" new file mode 100644 index 0000000..f90ed83 --- /dev/null +++ "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/12764_\354\213\270\354\247\200\353\260\251\354\227\220\352\260\204\354\244\200\355\225\230.py" @@ -0,0 +1,36 @@ +import sys +import heapq +input = sys.stdin.readline + +N = int(input()) +people = [tuple(map(int, input().split())) for _ in range(N)] + +pq_person = [] +pq_pc = [] +now_pc = 0 +pc_info_list = [0 for _ in range(N)] +person_idx2pc = [-1 for _ in range(N)] + +for idx, person in enumerate(people): + heapq.heappush(pq_person, (person[0], "Start", idx)) + heapq.heappush(pq_person, (person[1], "End", idx)) + +while pq_person: + item = heapq.heappop(pq_person) + idx = item[2] + if item[1] == "Start": + if pq_pc: + pc = heapq.heappop(pq_pc) + else: + pc = now_pc + now_pc += 1 + pc_info_list[pc] += 1 + person_idx2pc[idx] = pc + + else: + pc = person_idx2pc[idx] + heapq.heappush(pq_pc, pc) + +print(now_pc) +for item in pc_info_list[:now_pc]: + print(item, end=" ") diff --git "a/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_bin.py" "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_bin.py" new file mode 100644 index 0000000..4a51d8a --- /dev/null +++ "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_bin.py" @@ -0,0 +1,14 @@ +# 68ms +import sys +input = sys.stdin.readline + +n, k = map(int, input().split()) + +result = 0 + +while bin(n).count('1') > k: + first_one_index = bin(n)[::-1].index('1') + result += 2 ** first_one_index + n += 2 ** first_one_index + +print(result) diff --git "a/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_find_one.py" "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_find_one.py" new file mode 100644 index 0000000..4ea78dd --- /dev/null +++ "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_find_one.py" @@ -0,0 +1,22 @@ +import sys +input = sys.stdin.readline + +n, k = map(int, input().split()) + +result = 0 + + +def find_one(n): + one_count = 0 + while n != 0: + one_count += (n % 2) + n //= 2 + return one_count + + +while find_one(n) > k: + first_one_index = bin(n)[::-1].index('1') + result += 2 ** first_one_index + n += 2 ** first_one_index + +print(result) diff --git "a/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_find_one_and_idx.py" "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_find_one_and_idx.py" new file mode 100644 index 0000000..c81317f --- /dev/null +++ "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_find_one_and_idx.py" @@ -0,0 +1,30 @@ +import sys +input = sys.stdin.readline + +n, k = map(int, input().split()) + +result = 0 + + +def find_one_and_idx(n): + one_count = 0 + idx_cnt = 0 + first_one_idx = -1 + while n != 0: + if n % 2 == 1: + one_count += 1 + if first_one_idx == -1: + first_one_idx = idx_cnt + n //= 2 + idx_cnt += 1 + return one_count, first_one_idx + + +while True: + one_count, first_one_index = find_one_and_idx(n) + if one_count <= k: + break + result += 2 ** first_one_index + n += 2 ** first_one_index + +print(result) diff --git "a/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_\354\231\204\355\203\220.py" "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_\354\231\204\355\203\220.py" new file mode 100644 index 0000000..1c0ab3b --- /dev/null +++ "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1502_\353\254\274\353\263\221_\354\231\204\355\203\220.py" @@ -0,0 +1,23 @@ +# 완탐 -> pypy 통과 / python 미통과 +import sys +input = sys.stdin.readline + +n, k = map(int, input().split()) + + +def find_one(n): + one_count = 0 + while n != 0: + one_count += (n % 2) + n //= 2 + return one_count + + +result = 0 +while True: + one_count = find_one(n) + if one_count <= k: + print(result) + break + n += 1 + result += 1 diff --git "a/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1781_\354\273\265\353\235\274\353\251\264.py" "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1781_\354\273\265\353\235\274\353\251\264.py" new file mode 100644 index 0000000..8ea9ad2 --- /dev/null +++ "b/\354\235\230\354\247\204/240716_\355\236\231_\352\267\270\353\246\254\353\224\224_\352\265\254\355\230\204/1781_\354\273\265\353\235\274\353\251\264.py" @@ -0,0 +1,21 @@ +import sys +import heapq +input = sys.stdin.readline + +N = int(input()) +problems = [tuple(map(int, input().split())) for _ in range(N)] +deadline_list = [[] for _ in range(N+1)] + +for problem in problems: + deadline_list[problem[0]].append(problem[1]) + +pq = [] +ans = 0 +for deadline in range(N, 0, -1): + for item in deadline_list[deadline]: + heapq.heappush(pq, -item) + if pq: + solving = -heapq.heappop(pq) + ans += solving + +print(ans) diff --git "a/\354\235\230\354\247\204/240723_\352\267\270\353\246\254\353\224\224/8980_\355\203\235\353\260\260.py" "b/\354\235\230\354\247\204/240723_\352\267\270\353\246\254\353\224\224/8980_\355\203\235\353\260\260.py" new file mode 100644 index 0000000..3af3668 --- /dev/null +++ "b/\354\235\230\354\247\204/240723_\352\267\270\353\246\254\353\224\224/8980_\355\203\235\353\260\260.py" @@ -0,0 +1,24 @@ +# https://ddiyeon.tistory.com/36 +import sys +input = sys.stdin.readline + +N, C = map(int, input().split()) +M = int(input()) + +infos = [] +for _ in range(M): + s, r, box = map(int, input().split()) + infos.append((s, r, box)) +infos.sort(key=lambda x: x[1]) + +capa = [C]*N +total = 0 +for s, r, box in infos: + _min = C + for i in range(s, r): + if _min > min(capa[i], box): + _min = min(capa[i], box) + for i in range(s, r): + capa[i] -= _min + total += _min +print(total) diff --git "a/\354\235\230\354\247\204/240723_\352\267\270\353\246\254\353\224\224/nplus1_cardgame.py" "b/\354\235\230\354\247\204/240723_\352\267\270\353\246\254\353\224\224/nplus1_cardgame.py" new file mode 100644 index 0000000..2fdd396 --- /dev/null +++ "b/\354\235\230\354\247\204/240723_\352\267\270\353\246\254\353\224\224/nplus1_cardgame.py" @@ -0,0 +1,41 @@ +# https://velog.io/@oxboxx/n-1-%EC%B9%B4%EB%93%9C%EA%B2%8C%EC%9E%84-2024-%EC%B9%B4%EC%B9%B4%EC%98%A4-%EA%B2%A8%EC%9A%B8-%EC%9D%B8%ED%84%B4%EC%8B%AD-Python +from collections import deque + + +def solution(coin, cards): + N = len(cards) + initial = set(cards[:N//3]) + not_yet = deque(cards[N//3:]) + possible = set() + + def update_possible(): + if not_yet: + possible.add(not_yet.popleft()) + possible.add(not_yet.popleft()) + + # source에서 숫자 하나를 고르고, 그 숫자에 맞는 쌍을 target에서 찾습니다. + # 찾는 데 성공했다면 True를 반환하고, 실패했다면 False를 반환합니다. + def remove_pair(source: set, target: set) -> bool: + nonlocal coin, round + for x in list(source): + if N+1-x in target: + source.remove(x) + target.remove(N+1-x) + return True + return False + + round = 1 + while not_yet: + update_possible() + if remove_pair(initial, initial): + round += 1 + elif coin >= 1 and remove_pair(initial, possible): + coin -= 1 + round += 1 + elif coin >= 2 and remove_pair(possible, possible): + coin -= 2 + round += 1 + else: + break + + return round diff --git "a/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/17825_\354\243\274\354\202\254\354\234\204\354\234\267\353\206\200\354\235\264.py" "b/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/17825_\354\243\274\354\202\254\354\234\204\354\234\267\353\206\200\354\235\264.py" new file mode 100644 index 0000000..9fa99b1 --- /dev/null +++ "b/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/17825_\354\243\274\354\202\254\354\234\204\354\234\267\353\206\200\354\235\264.py" @@ -0,0 +1,63 @@ +import sys +import copy +dice_result = list(map(int, input().split())) + +board = {i: i*2 for i in range(20)} +board.update({99: 10, 100: 13, 101: 16, 102: 19, 199: 20, 200: 22, 201: 24, + 299: 30, 300: 28, 301: 27, 302: 26, 400: 25, 401: 30, 402: 35, + 500: 40, 600: 0}) +answer = 0 + + +def get_next_node(step, current_pos): + new_pos = step + current_pos + if new_pos == 5: + return 99 + if new_pos == 10: + return 199 + if new_pos == 15: + return 299 + if new_pos == 20 or new_pos == 403: + return 500 + if 20 < new_pos < 99 or 403 < new_pos < 499 or 500 < new_pos < 599: + return 600 + + if 201 < new_pos < 299: + new_pos = new_pos + 198 + if new_pos == 403: + return 500 + if new_pos > 403: + return 600 + + for i in [1, 3]: + if (i * 100 + 2) < new_pos < (i * 100 + 99): + new_pos = (new_pos - (i * 100) + 397) + if new_pos == 403: + return 500 + if new_pos == 404: + return 600 + return new_pos + return new_pos + + +def dfs(state, current_score, turn): + global answer + # print(state) + if turn == 10: + answer = max(answer, current_score) + return + for i in range(4): + if state[i] == 600: + continue + n_pos = get_next_node(dice_result[turn], state[i]) + # print(f"n_pos ={n_pos}") + if n_pos not in state or n_pos == 600: + cache = state[i] + state[i] = n_pos + # print(f"score={board[n_pos]}") + dfs(state, current_score + board[n_pos], turn + 1) + state[i] = cache + + +dfs([0, 0, 0, 0], 0, 0) +print(answer) diff --git "a/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/2110_\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.py" "b/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/2110_\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.py" new file mode 100644 index 0000000..a9640e8 --- /dev/null +++ "b/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/2110_\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.py" @@ -0,0 +1,31 @@ +import sys +input = sys.stdin.readline + +N, C = map(int, input().split()) +houses = [int(input()) for _ in range(N)] +houses.sort() + +start = 1 +end = houses[-1] - houses[0] + + +def is_possible(houses, test_dist): + remain = C-1 + current_house = houses[0] + for i in range(len(houses)-1): + if houses[i+1] - current_house >= test_dist: + current_house = houses[i+1] + remain -= 1 + if remain == 0: + return True + return False + + +while start <= end: + mid = (start + end) // 2 + if is_possible(houses, mid): + start = mid + 1 + else: + end = mid - 1 + +print(end) diff --git "a/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/2352_\353\260\230\353\217\204\354\262\264\354\204\244\352\263\204.py" "b/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/2352_\353\260\230\353\217\204\354\262\264\354\204\244\352\263\204.py" new file mode 100644 index 0000000..da9ac23 --- /dev/null +++ "b/\354\235\230\354\247\204/240806_\354\235\264\353\266\204\355\203\220\354\203\211_\352\265\254\355\230\204/2352_\353\260\230\353\217\204\354\262\264\354\204\244\352\263\204.py" @@ -0,0 +1,15 @@ +import sys +import bisect +input = sys.stdin.readline + +N = int(input()) +ports = list(map(int, input().split())) +lis = [] + +for port in ports: + if not lis or lis[-1] < port: + lis.append(port) + else: + lis[bisect.bisect_right(lis, port)] = port + +print(len(lis)) \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240813_\354\235\264\353\266\204\355\203\220\354\203\211_\355\210\254\355\217\254\354\235\270\355\204\260/15961_\355\232\214\354\240\204\354\264\210\353\260\245.py" "b/\354\235\230\354\247\204/240813_\354\235\264\353\266\204\355\203\220\354\203\211_\355\210\254\355\217\254\354\235\270\355\204\260/15961_\355\232\214\354\240\204\354\264\210\353\260\245.py" new file mode 100644 index 0000000..b7adb58 --- /dev/null +++ "b/\354\235\230\354\247\204/240813_\354\235\264\353\266\204\355\203\220\354\203\211_\355\210\254\355\217\254\354\235\270\355\204\260/15961_\355\232\214\354\240\204\354\264\210\353\260\245.py" @@ -0,0 +1,40 @@ +import sys +input = sys.stdin.readline + +N, d, k, c = map(int, input().split()) +items = [int(input()) for _ in range(N)] + +start = 0 +end = k-1 + +item_dict = {} +for i in range(k): + if item_dict.get(items[i]) is not None: + item_dict[items[i]] += 1 + else: + item_dict[items[i]] = 1 + +if item_dict.get(c) is not None: + item_dict[c] += 1 +else: + item_dict[c] = 1 + +max_val = len(item_dict.keys()) + +for _ in range(N): + if item_dict[items[start]] == 1: + del item_dict[items[start]] + else: + item_dict[items[start]] -= 1 + + start = (start + 1) % N + end = (end + 1) % N + + if item_dict.get(items[end]) is not None: + item_dict[items[end]] += 1 + else: + item_dict[items[end]] = 1 + + max_val = max(max_val, len(item_dict.keys())) + +print(max_val) diff --git "a/\354\235\230\354\247\204/240813_\354\235\264\353\266\204\355\203\220\354\203\211_\355\210\254\355\217\254\354\235\270\355\204\260/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\236\205\352\265\255\354\213\254\354\202\254.py" "b/\354\235\230\354\247\204/240813_\354\235\264\353\266\204\355\203\220\354\203\211_\355\210\254\355\217\254\354\235\270\355\204\260/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\236\205\352\265\255\354\213\254\354\202\254.py" new file mode 100644 index 0000000..dc7e1c1 --- /dev/null +++ "b/\354\235\230\354\247\204/240813_\354\235\264\353\266\204\355\203\220\354\203\211_\355\210\254\355\217\254\354\235\270\355\204\260/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\236\205\352\265\255\354\213\254\354\202\254.py" @@ -0,0 +1,23 @@ +def solution(n, times): + start = 1 + end = max(times) * n + + while start <= end: + mid = (start + end) // 2 + if is_possible(mid, n, times): + end = mid - 1 + else: + start = mid + 1 + + return start + + +def is_possible(test_t, n, times): + available = 0 + for time in times: + available += (test_t // time) + + if available >= n: + return True + else: + return False diff --git "a/\354\235\230\354\247\204/240827_DP/1149_RGB\352\261\260\353\246\254.py" "b/\354\235\230\354\247\204/240827_DP/1149_RGB\352\261\260\353\246\254.py" new file mode 100644 index 0000000..ea60e2a --- /dev/null +++ "b/\354\235\230\354\247\204/240827_DP/1149_RGB\352\261\260\353\246\254.py" @@ -0,0 +1,18 @@ +import sys +input = sys.stdin.readline + +N = int(input()) +prices = [tuple(map(int, input().split())) for _ in range(N)] + +dp = [] +dp.append([prices[0][i] for i in range(3)]) +for _ in range(N-1): + dp.append([0, 0, 0]) + +for i in range(1, N): + for j in range(3): + dp[i][j] = min(dp[i-1][((j+1) % 3)], dp[i-1][((j+2) % 3)]) +\ + prices[i][j] + + +print(min(dp[N-1])) \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240827_DP/11727_2xn\355\203\200\354\235\274\353\247\2012.py" "b/\354\235\230\354\247\204/240827_DP/11727_2xn\355\203\200\354\235\274\353\247\2012.py" new file mode 100644 index 0000000..00c21b1 --- /dev/null +++ "b/\354\235\230\354\247\204/240827_DP/11727_2xn\355\203\200\354\235\274\353\247\2012.py" @@ -0,0 +1,10 @@ +import sys +input = sys.stdin.readline +n = int(input()) + +dp = [0, 1, 3] + +for i in range(3, n + 1): + dp.append(2 * dp[i-2] + dp[i-1]) + +print(dp[n] % 10007) \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240827_DP/2156_\355\217\254\353\217\204\354\243\274\354\213\234\354\213\235.py" "b/\354\235\230\354\247\204/240827_DP/2156_\355\217\254\353\217\204\354\243\274\354\213\234\354\213\235.py" new file mode 100644 index 0000000..16c286e --- /dev/null +++ "b/\354\235\230\354\247\204/240827_DP/2156_\355\217\254\353\217\204\354\243\274\354\213\234\354\213\235.py" @@ -0,0 +1,30 @@ +import sys +input = sys.stdin.readline + +n = int(input()) +wines = [int(input()) for _ in range(n)] + +if n == 1: + print(wines[0]) + sys.exit() +elif n == 2: + print(wines[0] + wines[1]) + sys.exit() + +elif n == 3: + print(max(max(wines[0], wines[1]) + wines[2], wines[0] + wines[1])) + sys.exit() + +dp = [] + +dp.append(wines[0]) +dp.append(dp[0] + wines[1]) +dp.append(max(wines[0], wines[1]) + wines[2]) +dp.append(max(dp[0] + wines[2], dp[1]) + wines[3]) + +if n >= 4: + for i in range(4, n): + dp.append(max(dp[i-4] + wines[i-1], dp[i-3] + + wines[i-1], dp[i-2]) + wines[i]) + +print(max(dp[n-1], dp[n-2])) \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240903_DP/11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.py" "b/\354\235\230\354\247\204/240903_DP/11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.py" new file mode 100644 index 0000000..9c19749 --- /dev/null +++ "b/\354\235\230\354\247\204/240903_DP/11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.py" @@ -0,0 +1,16 @@ +import sys +input = sys.stdin.readline + +N = int(input()) +shapes = [tuple(map(int, input().split())) for _ in range(N)] + +dp = [[0] * N for _ in range(N)] + + +for i in range(1, N): + for j in range(N-i): + dp[j][j+i] = sys.maxsize + for k in range(j, j+i): + dp[j][j+i] = min(dp[j][j+i], dp[j][k] + dp[k+1][j+i] + shapes[j][0] * shapes[k][1] * shapes[j+i][1]) + +print(dp[0][N-1]) \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240903_DP/11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234_\354\265\234\354\240\201\355\231\224.py" "b/\354\235\230\354\247\204/240903_DP/11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234_\354\265\234\354\240\201\355\231\224.py" new file mode 100644 index 0000000..aa25f23 --- /dev/null +++ "b/\354\235\230\354\247\204/240903_DP/11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234_\354\265\234\354\240\201\355\231\224.py" @@ -0,0 +1,18 @@ +n = int(input()) + +arr = [list(map(int, input().split())) for _ in range(n)] +arr = [a for a, _ in arr] + [arr[-1][1]] +dp = [[0] * n for _ in range(n)] + +for step in range(1,n): + for loc in range(n-step): + end = loc + step + mul = arr[loc] * arr[end+1] + minimum = min(yk + xk + sz * mul for yk, xk, sz in zip(dp[loc][loc:end], dp[end][loc+1:end+1], arr[loc+1:end+1])) + dp[loc][end] = dp[end][loc] = minimum + +print(dp[0][-1]) + + +# 1. 1차원으로 Matrix Shape 접근 +# 2. Slicing과 Zip 함수 이용 -> 최적화된 실행을 보여줌 \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240903_DP/12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255.py" "b/\354\235\230\354\247\204/240903_DP/12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255.py" new file mode 100644 index 0000000..3c6d96d --- /dev/null +++ "b/\354\235\230\354\247\204/240903_DP/12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255.py" @@ -0,0 +1,19 @@ +import sys +input = sys.stdin.readline + +N, K = map(int, input().split()) +items = [tuple(map(int, input().split())) for _ in range(N)] + +dp = [[0] * (K+1) for _ in range(N)] + +for i in range(K+1): + if i >= items[0][0]: + dp[0][i] = items[0][1] + +for c in range(1, K+1): + for r in range(1, N): + dp[r][c] = dp[r-1][c] + if c-items[r][0] >= 0: + dp[r][c] = max(dp[r][c], dp[r-1][c-items[r][0]] + items[r][1]) + +print(dp[N-1][K]) \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240903_DP/2225_\355\225\251\353\266\204\355\225\264.py" "b/\354\235\230\354\247\204/240903_DP/2225_\355\225\251\353\266\204\355\225\264.py" new file mode 100644 index 0000000..4f86f6e --- /dev/null +++ "b/\354\235\230\354\247\204/240903_DP/2225_\355\225\251\353\266\204\355\225\264.py" @@ -0,0 +1,19 @@ +import sys +input = sys.stdin.readline + +N, K = map(int, input().split()) + +dp = [[0] * (K+1) for _ in range(N+1)] + +for i in range(N+1): + dp[i][1] = 1 +# for i in range(K+1): +# dp[0][i] = 1 + +for c in range(2, K+1): + for r in range(1, N+1): + dp[r][c] = dp[r-1][c] + dp[r][c-1] + +print(dp[N][K] % 1000000000) + + diff --git "a/\354\235\230\354\247\204/240910_DP/2662_\352\270\260\354\227\205\355\210\254\354\236\220.py" "b/\354\235\230\354\247\204/240910_DP/2662_\352\270\260\354\227\205\355\210\254\354\236\220.py" new file mode 100644 index 0000000..fbb862d --- /dev/null +++ "b/\354\235\230\354\247\204/240910_DP/2662_\352\270\260\354\227\205\355\210\254\354\236\220.py" @@ -0,0 +1,33 @@ +import sys +import copy +input = sys.stdin.readline + +N, M = map(int, input().split()) +enterprise_table = [[0, 0, 0]] + \ + [list(map(int, input().split())) for _ in range(N)] + +dp = [[0] * (N + 1) for _ in range(M+1)] +info = [[[]] * (N + 1) for _ in range(M+1)] + +for enterprise in range(1, M+1): + info[enterprise][0] = [0] * enterprise + +for weight in range(1, N+1): + dp[1][weight] = enterprise_table[weight][1] + info[1][weight] = [weight] + +for i in range(2, M+1): + for w_limit in range(N+1): + dp[i][w_limit] = dp[i-1][w_limit] + info[i][w_limit] = copy.copy(info[i-1][w_limit]) + info[i][w_limit].append(0) + for w_add in range(1, N+1): + if w_limit - w_add >= 0: + if dp[i][w_limit] < dp[i-1][w_limit - w_add] + enterprise_table[w_add][i]: + dp[i][w_limit] = dp[i-1][w_limit - w_add] + \ + enterprise_table[w_add][i] + info[i][w_limit] = copy.copy(info[i-1][w_limit-w_add]) + info[i][w_limit].append(w_add) + +print(dp[M][N]) +print(*info[M][N]) \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240924_\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274_\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234/20303_\355\225\240\353\241\234\354\234\210\354\235\230\354\226\221\354\225\204\354\271\230.py" "b/\354\235\230\354\247\204/240924_\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274_\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234/20303_\355\225\240\353\241\234\354\234\210\354\235\230\354\226\221\354\225\204\354\271\230.py" new file mode 100644 index 0000000..c3f9312 --- /dev/null +++ "b/\354\235\230\354\247\204/240924_\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274_\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234/20303_\355\225\240\353\241\234\354\234\210\354\235\230\354\226\221\354\225\204\354\271\230.py" @@ -0,0 +1,57 @@ +import sys +input = sys.stdin.readline + +N, M, K = map(int, input().split()) +candy = [0] + list(map(int, input().split())) +connections = [tuple(map(int, input().split())) for _ in range(M)] + +parents = [i for i in range(N+1)] +reward = [0] * (N+1) + +if K == 1: + print(0) + sys.exit() + +def find(x): + if parents[x] != x: + parents[x] = find(parents[x]) + return parents[x] + +def union(x, y): + parent_x = find(x) + parent_y = find(y) + if parent_x <= parent_y: + parents[parent_y] = parent_x + else: + parents[parent_x] = parent_y + + +for connection in connections: + union(connection[0], connection[1]) + +reward_info = {} +for i in range(1, N+1): + parent = find(i) + if reward_info.get(parent) is None: + reward_info[parent] = [candy[i] ,1] + else: + reward_info[parent][0] += candy[i] + reward_info[parent][1] += 1 + +reward_info = list(reward_info.values()) + +dp = [[0] * (len(reward_info)) for _ in range(K+1)] + +for i in range(K+1): + if i >= reward_info[0][1]: + dp[i][0] = reward_info[0][0] + +for i in range(1, len(reward_info)): + for j in range(1, K+1): + if j - reward_info[i][1] >= 0: + dp[j][i] = max(dp[j][i-1], dp[j-reward_info[i][1]][i-1] + reward_info[i][0]) + else: + dp[j][i] = dp[j][i-1] + +print(dp[-2][-1]) + \ No newline at end of file diff --git "a/\354\235\230\354\247\204/240924_\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274_\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234/20955_\353\257\274\354\204\234\354\235\230\354\235\221\352\270\211\354\210\230\354\210\240.py" "b/\354\235\230\354\247\204/240924_\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274_\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234/20955_\353\257\274\354\204\234\354\235\230\354\235\221\352\270\211\354\210\230\354\210\240.py" new file mode 100644 index 0000000..3140233 --- /dev/null +++ "b/\354\235\230\354\247\204/240924_\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274_\354\234\240\353\213\210\354\230\250\355\214\214\354\235\270\353\223\234/20955_\353\257\274\354\204\234\354\235\230\354\235\221\352\270\211\354\210\230\354\210\240.py" @@ -0,0 +1,33 @@ +import sys +input = sys.stdin.readline + +N, M = map(int, input().split()) +connections = [tuple(map(int, input().split())) for _ in range(M)] +parents = [i for i in range(N + 1)] + +def find(x): + if parents[x] != x: + parents[x] = find(parents[x]) # Path compression + return parents[x] + +def union(x, y): + parent_x = find(x) + parent_y = find(y) + if parent_x != parent_y: + if parent_x <= parent_y: + parents[parent_y] = parent_x + else: + parents[parent_x] = parent_y + +cut_cnt = 0 + +for x, y in connections: + if find(x) == find(y): + cut_cnt += 1 # Edge creates a cycle + else: + union(x, y) + +parent_set = set(find(i) for i in range(1, N + 1)) + +result = cut_cnt + len(parent_set) - 1 # -1 because we want to connect components +print(result) diff --git "a/\354\235\230\354\247\204/2\354\243\274\354\260\250_\354\212\244\355\203\235\355\201\220/2164_\354\271\264\353\223\2342.py" "b/\354\235\230\354\247\204/2\354\243\274\354\260\250_\354\212\244\355\203\235\355\201\220/2164_\354\271\264\353\223\2342.py" new file mode 100644 index 0000000..868a181 --- /dev/null +++ "b/\354\235\230\354\247\204/2\354\243\274\354\260\250_\354\212\244\355\203\235\355\201\220/2164_\354\271\264\353\223\2342.py" @@ -0,0 +1,24 @@ +import sys + +input = sys.stdin.readline +N = int(input()) +cards = [i for i in range(1, N+1)] + + +def solution_using_queue(cards): + while len(cards) > 1: + cards.pop(0) + cards.append(cards.pop(0)) + return cards[0] + + +def solution(cards): + while len(cards) > 1: + n = len(cards) + cards = cards[1::2] + if n % 2 == 1: + cards.append(cards.pop(0)) + return cards[0] + + +print(solution(cards)) diff --git "a/\354\235\230\354\247\204/2\354\243\274\354\260\250_\354\212\244\355\203\235\355\201\220/4949_\352\267\240\355\230\225\354\236\241\355\236\214\354\204\270\354\203\201.py" "b/\354\235\230\354\247\204/2\354\243\274\354\260\250_\354\212\244\355\203\235\355\201\220/4949_\352\267\240\355\230\225\354\236\241\355\236\214\354\204\270\354\203\201.py" new file mode 100644 index 0000000..e9e1394 --- /dev/null +++ "b/\354\235\230\354\247\204/2\354\243\274\354\260\250_\354\212\244\355\203\235\355\201\220/4949_\352\267\240\355\230\225\354\236\241\355\236\214\354\204\270\354\203\201.py" @@ -0,0 +1,28 @@ +import sys +input = sys.stdin.readline + +while True: + sentence = input().rstrip() + is_passed = True + if sentence == ".": + break + stack = [] + for char in sentence: + if char == "[" or char == "(": + stack.append(char) + elif char == "]": + if stack and stack[-1] == "[": + stack.pop() + else: + is_passed = False + break + elif char == ")": + if stack and stack[-1] == "(": + stack.pop() + else: + is_passed = False + break + if stack: + is_passed = False + + print("yes") if is_passed else print("no") diff --git "a/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/17148_\354\236\254\352\267\200\355\225\250\354\210\230\352\260\200\353\255\224\352\260\200\354\232\224.py" "b/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/17148_\354\236\254\352\267\200\355\225\250\354\210\230\352\260\200\353\255\224\352\260\200\354\232\224.py" new file mode 100644 index 0000000..c1873f4 --- /dev/null +++ "b/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/17148_\354\236\254\352\267\200\355\225\250\354\210\230\352\260\200\353\255\224\352\260\200\354\232\224.py" @@ -0,0 +1,33 @@ +import sys +input = sys.stdin.readline + +N = int(input()) + +print("어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.") + + +def execute_recursive_case(depth): + under_bar = 4 * depth * '_' + print(under_bar + '"재귀함수가 뭔가요?"') + print(under_bar + '"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.') + print(under_bar + '마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.') + print(under_bar + '그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어."') + recursive_func(depth + 1) + print(under_bar + "라고 답변하였지.") + + +def execute_base_case(): + under_bar = 4 * N * '_' + print(under_bar + '"재귀함수가 뭔가요?"') + print(under_bar + '"재귀함수는 자기 자신을 호출하는 함수라네"') + print(under_bar + "라고 답변하였지.") + + +def recursive_func(depth): + if depth == N: + execute_base_case() + else: + execute_recursive_case(depth) + + +recursive_func(0) diff --git "a/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/2563_\354\203\211\354\242\205\354\235\264.py" "b/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/2563_\354\203\211\354\242\205\354\235\264.py" new file mode 100644 index 0000000..4a51fef --- /dev/null +++ "b/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/2563_\354\203\211\354\242\205\354\235\264.py" @@ -0,0 +1,12 @@ +import sys +input = sys.stdin.readline + +n = int(input()) +colored_papers = [tuple(map(int, input().split())) for _ in range(n)] +board = [[0] * 100 for _ in range(100)] + +for colored_paper in colored_papers: + for row in range(colored_paper[1], colored_paper[1] + 10): + board[row][colored_paper[0]: colored_paper[0] + 10] = [1] * 10 + +print(sum([board[i].count(1) for i in range(len(board))])) diff --git "a/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/2941_\355\201\254\353\241\234\354\225\204\355\213\260\354\225\204\354\225\214\355\214\214\353\262\263.py" "b/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/2941_\355\201\254\353\241\234\354\225\204\355\213\260\354\225\204\354\225\214\355\214\214\353\262\263.py" new file mode 100644 index 0000000..c13b706 --- /dev/null +++ "b/\354\235\230\354\247\204/3\354\243\274\354\260\250_\352\265\254\355\230\204\354\236\254\352\267\200/2941_\355\201\254\353\241\234\354\225\204\355\213\260\354\225\204\354\225\214\355\214\214\353\262\263.py" @@ -0,0 +1,69 @@ +import sys +input = sys.stdin.readline + +string = input().rstrip() + +idx = 0 +answer = 0 +while idx < len(string): + char = string[idx] + match char: + case "l": + if idx + 1 < len(string) and string[idx:idx+2] == "lj": + answer += 1 + idx += 2 + else: + answer += 1 + idx += 1 + case "n": + if idx + 1 < len(string) and string[idx:idx+2] == "nj": + answer += 1 + idx += 2 + else: + answer += 1 + idx += 1 + case "s": + if idx + 1 < len(string) and string[idx:idx+2] == "s=": + answer += 1 + idx += 2 + else: + answer += 1 + idx += 1 + case "z": + if idx + 1 < len(string) and string[idx:idx+2] == "z=": + answer += 1 + idx += 2 + else: + answer += 1 + idx += 1 + + case "c": + if idx + 1 < len(string): + if string[idx:idx+2] == "c=": + answer += 1 + idx += 2 + elif string[idx:idx+2] == "c-": + answer += 1 + idx += 2 + else: + answer += 1 + idx += 1 + else: + answer += 1 + idx += 1 + + case "d": + if idx + 1 < len(string) and string[idx:idx+2] == "d-": + answer += 1 + idx += 2 + + elif idx + 2 < len(string) and string[idx:idx+3] == "dz=": + answer += 1 + idx += 3 + else: + answer += 1 + idx += 1 + case _: + answer += 1 + idx += 1 +print(answer) diff --git "a/\354\235\230\354\247\204/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/13164_\355\226\211\353\263\265\354\234\240\354\271\230\354\233\220.py" "b/\354\235\230\354\247\204/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/13164_\355\226\211\353\263\265\354\234\240\354\271\230\354\233\220.py" new file mode 100644 index 0000000..a36f633 --- /dev/null +++ "b/\354\235\230\354\247\204/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/13164_\355\226\211\353\263\265\354\234\240\354\271\230\354\233\220.py" @@ -0,0 +1,20 @@ +import sys +input = sys.stdin.readline + +N, K = map(int, input().split()) +students = list(map(int, input().split())) + +diff_list = [] +diff_sum = 0 + +for i in range(len(students)-1): + diff = students[i+1] - students[i] + diff_sum += diff + diff_list.append(diff) + +diff_list.sort(reverse=True) + +for diff in diff_list[:K-1]: + diff_sum -= diff + +print(diff_sum) diff --git "a/\354\235\230\354\247\204/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/1082_\353\260\251\353\262\210\355\230\270.py" "b/\354\235\230\354\247\204/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/1082_\353\260\251\353\262\210\355\230\270.py" new file mode 100644 index 0000000..b1938cd --- /dev/null +++ "b/\354\235\230\354\247\204/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/1082_\353\260\251\353\262\210\355\230\270.py" @@ -0,0 +1,62 @@ +import sys +input = sys.stdin.readline + +N = int(input()) +prices = list(map(int, input().split())) +budget = int(input()) + +if N == 1: + print(0) + sys.exit() + +# 1. 자리수 결정 +num_and_prices = [] +for num, price in enumerate(prices): + num_and_prices.append((price, num)) + +num_and_prices.sort(key=lambda x: (x[0], -x[1])) + +budget_for_digit_det = budget +if num_and_prices[0][1] == 0: + budget_for_digit_det -= num_and_prices[1][0] + if budget_for_digit_det < 0: + print(0) + sys.exit() + msd = num_and_prices[1][1] + digit_cnt = budget_for_digit_det // num_and_prices[0][0] + remainer = budget_for_digit_det % num_and_prices[0][0] + standard_num_str = str(msd) + ("0" * digit_cnt) + +else: + msd = num_and_prices[0][1] + digit_cnt = budget_for_digit_det // num_and_prices[0][0] + remainer = budget_for_digit_det % num_and_prices[0][0] + standard_num_str = str(msd) * digit_cnt + +if len(standard_num_str) == 0: + print(0) + sys.exit() + +# 2. 큰 수로 대체 + + +def get_replacing_cost(past, new): + past_price = prices[past] + new_price = prices[new] + replacing_cost = new_price - past_price + return replacing_cost + + +standard_num_list = list(standard_num_str) +for i, digit in enumerate(standard_num_list): + for new in range(N-1, int(digit), -1): + replacing_cost = get_replacing_cost(int(digit), new) + if replacing_cost <= remainer: + standard_num_list[i] = new + remainer -= replacing_cost + break + +answer = "" +for digit in standard_num_list: + answer += str(digit) +print(int(answer)) diff --git "a/\354\235\230\354\247\204/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/16234_\354\235\270\352\265\254\354\235\264\353\217\231.py" "b/\354\235\230\354\247\204/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/16234_\354\235\270\352\265\254\354\235\264\353\217\231.py" new file mode 100644 index 0000000..59c5aa8 --- /dev/null +++ "b/\354\235\230\354\247\204/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/16234_\354\235\270\352\265\254\354\235\264\353\217\231.py" @@ -0,0 +1,73 @@ +import sys +from collections import deque +input = sys.stdin.readline + +N, L, R = map(int, input().split()) +populations = [list(map(int, input().split())) for _ in range(N)] +dx = [1, -1, 0, 0] +dy = [0, 0, 1, -1] +count = 1 +visited = [[0] * N for _ in range(N)] +results = [0] + + +def bfs(r, c, area_num): + is_changed = False + q = deque() + q.append((r, c)) + visited[r][c] = area_num + population_count = populations[r][c] + nation_count = 1 + next = set() + changed_nation = set() + while q: + y, x = q.popleft() + candidate_count = 0 + for i in range(4): + nx = x + dx[i] + ny = y + dy[i] + + if 0 <= nx < N and 0 <= ny < N and visited[ny][nx] == area_num: + candidate_count += 1 + + if 0 <= nx < N and 0 <= ny < N and visited[ny][nx] == 0 and L <= abs(populations[y][x] - populations[ny][nx]) <= R: + visited[ny][nx] = area_num + population_count += populations[ny][nx] + nation_count += 1 + is_changed = True + candidate_count += 1 + q.append((ny, nx)) + if 1 <= candidate_count <= 3: + next.add((y, x)) + if candidate_count >= 1: + changed_nation.add((y, x)) + results.append(population_count // nation_count) + return is_changed, next, changed_nation + + +is_changed = True +result_count = 0 +new_candidate = {(r, c) for r in range(N) for c in range(r % 2, N, 2)} +next_candidate = set() +while is_changed: + results = [0] + visited = [[0] * N for _ in range(N)] + is_changed = False + visited_count = 0 + next_candidate = new_candidate + new_candidate = set() + changed_nation = set() + for r, c in next_candidate: + if not visited[r][c]: + visited_count += 1 + if is_changed is False: + is_changed, next, changed = bfs(r, c, visited_count) + else: + _, next, changed = bfs(r, c, visited_count) + new_candidate = next | new_candidate + changed_nation = changed | changed_nation + for r, c in changed_nation: + populations[r][c] = results[visited[r][c]] + if is_changed is True: + result_count += 1 +print(result_count) diff --git "a/\355\230\204\354\244\221/10\354\243\274\354\260\250/1715_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.cpp" "b/\355\230\204\354\244\221/10\354\243\274\354\260\250/1715_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.cpp" new file mode 100644 index 0000000..0629f29 --- /dev/null +++ "b/\355\230\204\354\244\221/10\354\243\274\354\260\250/1715_\354\271\264\353\223\234\354\240\225\353\240\254\355\225\230\352\270\260.cpp" @@ -0,0 +1,63 @@ +// 1715 카드정렬하기 + +// 카드를 정렬하는데 비교해야하는 최소의 횟수를 구하자 +// 이는 가장 적은 2개의 묶음을 우선적으로 계산하는 것 -> 힙으로 +// 카드 묶음을 합치는 횟수 : N-1 + + + +#include +#include + +#define MAX 10000 + +using namespace std; + +int N; //카드묶음 +int Arr[MAX]; + +void Input(){ + cin >> N; // 카드 묶음 수 + for(int i=0; i> Arr[i]; // 각 카드 묶음 크기 + } +} + +void solution(){ + priority_queue PQ; //최소힙 + for(int i=0; i 불이 먼저 이동하고 상근이가 이동해야 됌 + +#include +#include // FIFO구조 + +#define MAX 1000 +1 // 지도 너비w 높이h 최대 크기 +#define X second +#define Y first + +using namespace std; + +int dx[4] = {0,0,1,-1}; +int dy[4] = {1,-1,0,0}; + +char map[MAX][MAX]; +int w,h; + +queue > sq; // 상근이 위치 +queue > fq; // 불의 위치 + + +// 불이 퍼져나가는 것을 구현하는 함수 +void MoveFire(){ + int cnt = fq.size(); // 현재 불의 위치 갯수를 고정 + for(int i=0; i cur = fq.front(); // (queue의 맨 앞에 있는) 현재위치 불의 위치를 가져와 + fq.pop(); // 처리한 불의 위치 제거 + + for(int dir = 0; dir <4; dir++){ // 불이 상하좌우로 퍼짐 + int nx = cur.X + dx[dir]; + int ny = cur.Y + dy[dir]; + + if(ny<0 || nx<0 || nx >= h || ny>=w) // 경계밖이면 + continue; // 다음 방향으로 이동 + if(map[ny][nx] !='.') // 빈공간이 아닌 경우 + continue; + + map[ny][nx] = '*'; //불을 퍼뜨리고 + fq.push({ny,nx}); // 해당위치를 큐에 추가 + } + } + +} + + +// 상근이가 이동하는 함수 +int MoveS(){ + int time =0; // 탈출시간 초기화 + while(!sq.empty()){ + time++; //1. 시간 +1하면 + MoveFire(); // 2. 불이 먼저 이동 (탐색전 MoveFire를 호출하여 불이 먼저 움직인 다음 상근이가 움직이게) + + int cnt = sq.size(); // 3. 현재 상근이 위치 수를 고정하고 + for (int i=0; i< cnt; i++){ + pair cur = sq.front(); // 앞에 있는 상근이의 위치를 가져와서 + sq.pop(); // 처리한 상근이의 위치를 queue에서 제거 + for(int dir=0; dir<4; dir++){ // 상근이의 현재 위치 상하좌우 이동 + int nx = cur.X + dx[dir]; + int ny = cur.Y + dy[dir]; + + if(ny<0 || nx<0 || nx >= h || ny>=w) // 경계조건을 + return time; // 벗어나면 탈출에 성공한 것으로 현재 시간을 반환 + if(map[ny][nx] !='.') // 빈공간이 아니면 다음 방향 시도 + continue; + + map[ny][nx] = '@'; // 새로운 위치에 상근이 추가 + sq.push({ny,nx}); // 새로운 위치를 queue에 추가 + + + } + } + } + + return -1; //queue가 비어있을대가지 탈출하지 못한 경우 탈출 불가 +} + + +// testcase별 지도 초기화 +void Reset(int w, int h){ + for(int y=0; y> t; // 입력1 testcase 갯수 + + for(int i=0; i> w>> h; // 입력2 너비, 높이 + for(int y=0; y> map[y][x]; // 입력3 격자의 각 위치의 내용 입력 + + if(map[y][x] == '@')// 상근이 초기 위치 queue에 저장 + sq.push({y,x}); + else if(map[y][x] == '*') // 불 초기 위치 queue에 저장 + fq.push({y,x}); + } + } + + int time = MoveS(); // 상근 탈출 시간 계산 + + if (time == -1) + cout << "IMPOSSIBLE" << endl; // 탈출x + else + cout<< time << endl; // 출력 탈출 + + Reset(w,h); // 각 testcase마다 상태 초기화 + } + + return 0; + +} + + + + + + diff --git "a/\355\230\204\354\244\221/11\354\243\274\354\260\250/127643_\354\213\270\354\247\200\353\260\251\354\227\220 \352\260\204 \354\244\200\355\225\230.cpp" "b/\355\230\204\354\244\221/11\354\243\274\354\260\250/127643_\354\213\270\354\247\200\353\260\251\354\227\220 \352\260\204 \354\244\200\355\225\230.cpp" new file mode 100644 index 0000000..0e541aa --- /dev/null +++ "b/\355\230\204\354\244\221/11\354\243\274\354\260\250/127643_\354\213\270\354\247\200\353\260\251\354\227\220 \352\260\204 \354\244\200\355\225\230.cpp" @@ -0,0 +1,63 @@ +// 싸지방에 간 준하 + +#include +#include +#include +#include + + +using namespace std; + +int main(){ + ios_base::sync_with_stdio(false); + cin.tie(); + + int N; // 사람의 수 + cin >> N; + + priority_queue, vector>, greater<>> min_heap; // <시작시간, 좌석번호> + priority_queue, vector>, greater<>> seat; // <좌석번호, 끝나는시간> + vector>time; + vectorcnt(N); + int ans = 0; + + for(int i=0; i>start>>end; + time.push_back({start,end}); + } + + sort(time.begin(),time.end()); + int computer_num = 0; + + for(int i=0; i + +using namespace std; + +int N; +int main() +{ + cin >> N; // 설탕무게 + int ans = 0; // 봉지갯수 + while (N >= 0) + { + if (N % 5 == 0) + { // 5로 나눌 수 있는가? + ans += (N / 5); // 있다면 몫이 정답 + cout << ans << endl; + return 0; + } + // 5로 나눌 수 없는가? + N -= 3; // 3kg을 빼고 + ans++; // 3키로 설탕가방 +1 + } + cout << -1 << endl; // 5,3으로 나눌수 없으면 -1출력 +} + +// 2.DP +#include + +using namespace std; + +int dp[5001]; + +int main() +{ + int n; + cin >> n; + // 3,5kg를 만드는 가장 최소의 봉지수 = 1 + dp[3] = dp[5] = 1; + + // 3과 5 다음 6부터 + for (int i = 6; i <= n; i++) + { + if (dp[i - 3]) + dp[i] = dp[i - 3] + 1; + + // dp[i-3]에 값이 존재 : dp[i]가 업데이트 됐었을 수 있다. + // dp[i]에 값이 없다면 : dp[i] = dp[i-5] +1 로 업데이트 + if (dp[i - 5]) + dp[i] = dp[i] ? min(dp[i], dp[i - 5] + 1) : dp[i - 5] + 1; + } + + cout << (dp[n] == 0 ? -1 : dp[n]) << endl; + + return 0; +} diff --git "a/\355\230\204\354\244\221/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\353\257\270\353\241\234\355\203\220\354\203\211.cpp" "b/\355\230\204\354\244\221/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\353\257\270\353\241\234\355\203\220\354\203\211.cpp" new file mode 100644 index 0000000..0e1910b --- /dev/null +++ "b/\355\230\204\354\244\221/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\353\257\270\353\241\234\355\203\220\354\203\211.cpp" @@ -0,0 +1,2 @@ +// 미로탐색 + diff --git "a/\355\230\204\354\244\221/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\234\240\352\270\260\353\206\215\353\260\260\354\266\224.cpp" "b/\355\230\204\354\244\221/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\234\240\352\270\260\353\206\215\353\260\260\354\266\224.cpp" new file mode 100644 index 0000000..81f8e13 --- /dev/null +++ "b/\355\230\204\354\244\221/5\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\234\240\352\270\260\353\206\215\353\260\260\354\266\224.cpp" @@ -0,0 +1,75 @@ +// 유기농 배추 dfs +// 배추구역이 몇개? -> dfs : 이미 탐색한 구역의 배추인지 방문표시, 주변조사 + +#include +#include + +using namespace std; + +// 첫줄에는 테스트 케이스의 갯수 T가 주어짐 + +// 입력 +int n; // 배추밭의 세로길이 1=0 && next_y >=0 && next_x < m && next_y 해당지역 방문처리 + dfs(next_y, next_x); + } + return true; +} + +// 배추 군집의 수를 계산 +int main(void){ + int TC; + scanf ("%d", &TC); + for(int i =0; i< TC; i++){ //testcase loop 초기화 + scanf("%d %d %d", &m, &n, &cabbage); + memset(a,0, sizeof(a)); // 배추가 심어진 위치를 저장하는 배열을 초기화 + memset(check,0,sizeof(check)); // check 배열을 초기화 + + + for (int j = 0; j < cabbage; j++) + { + int x=0, y=0; + scanf("%d %d", &x, &y); + a[y][x] = 1; + } + + int bug_count =0; //배추의 군집수를 count + + + //2. 전체 칸 조사 -> 배추가 있을 경우 조사하지 않은 구역이라면 dfs를 통해 주변에 다른 배추가 있는지 조사 + for(int j = 0; j + +using namespace std; + +int N, M; // N-1 : 까지 숫자, M : 금액 +int cost[10]; +int ans[51]; + +void solve() { + int h_min = 1, r_min = 0, idx = 1; + for (int i = 0; i < N; i++) { + if (cost[i] <= cost[r_min]) + r_min = i; + } + + if (r_min == 0) { + for (int i = 1; i < N; i++) { + if (cost[i] <= cost[h_min]) + h_min = i; + } + } + else h_min = r_min; + + if (M < cost[h_min] || N == 1) { + cout << "0"; + return; + } + ans[0] = h_min; + M -= cost[h_min]; + while (1) { + if (M - cost[r_min] < 0) + break; + M -= cost[r_min]; + ans[idx++] = r_min; + } + for (int i = N - 1; i > h_min; i--) { + if (M - (cost[i] - cost[h_min]) >= 0) { + ans[0] = i; + M -= (cost[i] - cost[h_min]); + break; + } + } + int p = 1, reduce = cost[r_min]; + for (int i = 0; i < N; i++) { + cost[i] = cost[i] - reduce; + } + while (1) { + int tmp = ans[p]; + for (int i = N - 1; i >= 0; i--) { + if (M - cost[i] >= 0) { + ans[p] = i; + M -= cost[i]; + break; + } + } + if (tmp == ans[p]) break; + p++; + } + + + for (int i = 0; i < idx; i++) { + cout << ans[i]; + } + +} + +int main() { + ios::sync_with_stdio(0); + cin.tie(0); cout.tie(0); + + cin >> N; + for (int i = 0; i < N; i++) { + cin >> cost[i]; + } + cin >> M; + solve(); +} \ No newline at end of file diff --git "a/\355\230\204\354\244\221/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\235\270\352\265\254\354\235\264\353\217\231_update.cpp" "b/\355\230\204\354\244\221/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\235\270\352\265\254\354\235\264\353\217\231_update.cpp" new file mode 100644 index 0000000..78d5e8f --- /dev/null +++ "b/\355\230\204\354\244\221/7\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\235\270\352\265\254\354\235\264\353\217\231_update.cpp" @@ -0,0 +1,104 @@ +// 인구이동 bfs : 너비우선 +// 개어렵네 야발 10번 풀면 익숙해질듯 + +#include +#include +#include +#include //절대값 계산하기 위해 + +using namespace std; +#define MAX 51 + +// 땅의크기 : N*N +// 국경선 open : 1< L< 인구차이 > q; // bfs 탐색을 위한 queue +vector> v; // 연합된 국가들의 좌표들을 저장할 벡터 / v size(1) = 국경선 열리는 곳 x + +bool flag = true; // 연합여부 +int sum =0; // 평균을 구하기 위해 + + +// Queue를 사용하여 인접한 좌표를 탐색, 조건에 맞으면 연합에 추가 및 재분배 +void bfs(pair start){ // bfs를 시작할 좌표를 queue에 추가 + q.push(start); + visited[start.first][start.second] = true; // 시작할 좌표를 방문처리 + + while(!q.empty()){ // queue가 빌때까지 반복 + pair temp = q.front(); // queue의 맨 앞 좌표 가져오기 + q.pop(); // queue의 맨 앞 좌표 제거 + + for(int i =0; i <4; i++){ // 동서남북 탐색 + int new_x = temp.first + dx[i]; + int new_y = temp.second + dy[i]; + + // 1. 범위 안에 있고 2. 방문하지 않으며 3. 인구차이가 조건에 맞음 + if(new_x>=0 && new_y>=0 && new_x < N && new_y < N && !visited[new_x][new_y]){ + if( abs(arr[new_x][new_y] - arr[temp.first][temp.second]) >=L && abs(arr[new_x][new_y] - arr[temp.first][temp.second]) <=R ){ + q.push({new_x, new_y}); //1. queue에 새로운 좌표를 추가하여 다음 탐색 노드 설정 + visited[new_x][new_y] = true; //2. 방문처리 + v.push_back({new_x,new_y}); //3. 연합된 국가벡터에 새로운 좌표 추가하여 연합에 포함된 국가 목록 추가 + sum += arr[new_x][new_y]; //4. 연합된 인구 합계에 새로운 좌표의 인구수를 추가하여 연합된 인구수 계산 + + } + } + + } + } + +} + + +void clear(){ // visited 배열을 초기화 -> 왜해줘야해????????????? + for(int i =0; i> N >> L >> R; // 입력값 받기 + for(int i = 0; i> arr[i][j]; // 각 위치의 인구 수 입력받기 + } + } + + + while(flag){ // 연합이 일어나는 한 계속 반봅 + flag = false; // 연합 초기화 + for(int i=0; i < N; i++){ + for(int j=0; j < N; j++){ + if(!visited[i][j]){ + v.clear(); + v.push_back({i,j}); + sum = arr[i][j]; + bfs({i,j}); + } + + if(v.size()>=2){ + flag = true; + for(int i=0; i +#include +#include // 문자열의 빈도를 해시맵에 저장 + +using namespace std; + +struct pos +{ + int r; + int c; +}; + +//3 cnt; // 문자열의 빈도를 저장 + +//격자 내부에 있는지 확인함수 +bool in_range(pos p) +{ + if (p.r <0 || p.r >=N || p.c <0 || p.c >=M) + return false; + else + return true; +} + +// 새로운위치를 저장하는 함수 << 현재위치 + 이동방향 +pos get_pos(pos currunt, int d) +{ + int dr[] = {-1, -1, -1, 1, 1, 1, 0, 0}; + int dc[] = {-1, 0, 1, -1, 0, 1, 1, -1}; + /*int dr[] = {-1,-1,-1,1,1,1,0,0}; + int dc[] = {-1,0,1,-1,0,1,1,-1};*/ + + pos next; + next.r = currunt.r + dr[d]; + next.c = currunt.c + dr[d]; + + // 3x3일때 범위 벗어나는경우 + if(next.r<0) next.r = N-1; // 위로넘어감 0,1 -> 2,1 + if(next.r>=N) next.r = 0; // 아래로넘어감 2,1 -> 0,1 + if(next.c<0) next.c = M-1; // 왼쪽으로 넘어감 1,0 -> 1,2 + if(next.c>=M) next.c = 0; // 오른쪽으로 넘어감 1,2 -> 1,0 + + return next; +} + +//경로를 탐색 -> 문자열 생성 -> cnt +void dfs(pos curr, string s) +{ + int i; + + s += board[curr.r][curr.c]; + cnt[s]++; + + + if(s.size() == 5) + return; + + // 모든방향으로 dfs + for(i=0; i<8; i++) //8방향 + dfs(get_pos(curr, i), s); +} + +int main() +{ + int i; + string s; + pos p; + + /*ios::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL);*/ + + cin>>N>>M>>K; + + for(i = 0; i < N; i++) + { + cin >> board[i]; + } + + // dfs를 호출하여 모든 좌표에서 시작하여 만들수 있는 문자열 생성 + for(p.r=0; p.r> s; + cout << cnt[s] << "\n"; + } + + return 0; +} + + + + + + diff --git "a/\355\230\204\354\244\221/8\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\247\200\352\265\254\354\230\250\353\202\234\355\231\224.cpp" "b/\355\230\204\354\244\221/8\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\247\200\352\265\254\354\230\250\353\202\234\355\231\224.cpp" new file mode 100644 index 0000000..b7e35b3 --- /dev/null +++ "b/\355\230\204\354\244\221/8\354\243\274\354\260\250_bfsdfs_\352\267\270\353\246\254\353\224\224/\354\247\200\352\265\254\354\230\250\353\202\234\355\231\224.cpp" @@ -0,0 +1,59 @@ +// 지구온난화 + +#include +#include + +using namespace std; + + +int R,C; + +vector grid, result; + +// 인접한 바다의 갯수 +int count_adjacent_sea(int r, int c){ + int dr[] = {-1, 1, 0, 0}; + int dc[] = {0, 0, -1, 1}; + int cnt = 0; + + + for(int i=0; i<4; i++){ + int nr = r + dr[i]; + int nc = c + dc[i]; + + if(nr <0 || nr >=R || nc <0 || nc >=C || grid[nr][nc] == '.'){ + cnt ++; + } + } + + return cnt; +} + +int main(){ + cin >>R>>C; + grid.resize(R); // R개의 길이 + result.resize(R, string(C, '.')); // C인 문자열 초기화 + + for(int i=0; i> grid[i]; + } + + for(int r=0; r=3){ + result[r][c] = '.'; + } + else{ + result[r][c] = 'x'; + } + } + } + } +return 0; + +} + + + + diff --git "a/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/Router installation.cpp" "b/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/Router installation.cpp" new file mode 100644 index 0000000..93570d4 --- /dev/null +++ "b/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/Router installation.cpp" @@ -0,0 +1,76 @@ +// Router_installation + +// N개의 집이 수직선 (2 < N < 200,000) (0 < x < 1,000,000,000) +// C개의 공유기 설치 (2 < C < N) +// 가장 인접한 두 공유기C 사이거리를 최대!! + +// 핵심 +// 1. +// 2. 인접한 공유기들의 간격이 최대가 된게 설치되기를 원함 +// 3. 따라서 집의 위치보다는 집 사이 거리가 중요 +// 4. 최대 거리의 mid_dist를 구하여 이분탐색하자 + +// 풀이 +// 1. 집 위치 좌표를 오름차순으로 정렬 +// 2. 최대간격을 구한 후, mid_dist를 기준으로 시작 +// 3. mid_dist를 기준으로 탐색을 한 후 공유기 갯수대로 설치를 못하면 F를 때리고, 그 이상은 다 F +// 4. T가 나온다면 또 반복하여 T가 나오는 가장 큰 dist를 구하자 + +#include +#include +#include + +using namespace std; + +int main() +{ + int n, c; // n : 집의 갯수, c : 공유기 갯수 + cin >> n >> c; + vector houses(n); // [1,2,4,8,9] + + // 집 좌표를 입력으로 받아서 + for (int i = 0; i < n; i++) + { + cin >> houses[i]; + } + + // 오름차순으로 정리하고 + sort(houses.begin(), houses.end()); + + // 최대거리 구해 + int min_dist = 1; // 최소거리 + int max_dist = houses[n - 1] - houses[0]; // 최대거리 + int ans = 0; + + // 이분탐색 + while (min_dist <= max_dist) + { + int mid_dist = (min_dist + max_dist) / 2; // mid_dist = 4 + int cnt = 1; // 첫번째 집은 설치했다 가정 후, 설치 cnt + int install = houses[0]; // 설치 + + // 첫번째 집은 이미 설치했다하고 두번째 집부터 mid_dist 이상인지 탐색 + for (int i = 1; i < n; i++) + { + if ((houses[i] - install) >= mid_dist) + { // 집 - 설치 >= mid_dist + cnt++; + install = houses[i]; // 공유기가 설치된 집의 위치를 저장 후 현재집은 기준으로 다시 거리 측정 + } + } + + // 설치한 공유기 갯수가 c개 미만이면 mid_dist 간격은 True, c 미만이면 False + if (cnt < c) + { + max_dist = mid_dist - 1; // mid_dist가 너무 커서 c갯수 만큼 설치 못할 경우 mid_dist를 내리기 ex) 4-> 2 + } + else + { + ans = mid_dist; + min_dist = mid_dist + 1; // mid_dist가 작아 c갯수 이상일 때, mid_dist를 늘려서 해보기 ex) 2->3 + } + } + + cout << ans << '\n'; + return 0; +} diff --git "a/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/integrated circuit design.cpp" "b/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/integrated circuit design.cpp" new file mode 100644 index 0000000..cfb2950 --- /dev/null +++ "b/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/integrated circuit design.cpp" @@ -0,0 +1,32 @@ +// integrated circuit design + +// 선이 꼬이지 않게 설계 +// 1< n < 40,000 + +#include +#include +#include + +#define MAX = 40000 + +using namespace std; + +// n개의 port +int N; +int Arr[MAX]; // 수열을 저장할 배열 + +vector V; // LIS를 저장할 벡터 + +void Input() +{ + cin >> N; + for (int i = 0; i <= N; i++) + { + cin >> Arr[i]; + } +} + +// LIS +void Solution() +{ +} \ No newline at end of file diff --git "a/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/roll_dice.cpp" "b/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/roll_dice.cpp" new file mode 100644 index 0000000..db85c98 --- /dev/null +++ "b/\355\230\204\354\244\221/Router installation, integrated circuit design, roll_dice/roll_dice.cpp" @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#define endl "\n" +using namespace std; + +int dice[10]; +array, 33> board = {{{0, 1, 2, 3, 4, 5}, + {2, 3, 4, 5, 6, 7}, + {4, 5, 6, 7, 8, 9}, + {6, 7, 8, 9, 10, 11}, + {8, 9, 10, 11, 12, 13}, + {10, 11, 12, 13, 14, 15}, + {12, 13, 14, 15, 16, 17}, + {14, 15, 16, 17, 18, 19}, + {16, 17, 18, 19, 20, 21}, + {18, 19, 20, 21, 22, 23}, + {20, 21, 22, 23, 24, 25}, + {22, 23, 24, 25, 26, 27}, + {24, 25, 26, 27, 28, 29}, + {26, 27, 28, 29, 30, 31}, + {28, 29, 30, 31, 32, 32}, + {30, 32, 32, 32, 32, 32}, + {28, 30, 32, 32, 32, 32}, + {27, 29, 30, 32, 32, 32}, + {26, 28, 29, 30, 32, 32}, + {25, 27, 28, 29, 30, 32}, + {20, 26, 27, 28, 29, 30}, + {21, 25, 26, 27, 28, 29}, + {23, 24, 25, 26, 27, 28}, + {22, 23, 24, 25, 26, 27}, + {24, 25, 26, 27, 28, 29}, + {25, 27, 28, 29, 30, 32}, + {26, 28, 29, 30, 32, 32}, + {27, 29, 30, 32, 32, 32}, + {30, 32, 32, 32, 32, 32}, + {28, 30, 32, 32, 32, 32}, + {27, 31, 24, 25, 26, 20}, + {26, 24, 25, 26, 20, 32}}}; +int ans = 0; + +void dfs(array pawn, int diceIndex, int score) +{ + bool startZero = false; + for (int i = 0; i < 4; ++i) + { + if (pawn[i] == 0) + { + if (startZero) + continue; + else + startZero = true; + } + else if (pawn[i] == 32) + { + continue; + } + int ti = board[pawn[i]][dice[diceIndex]]; + if (find(pawn.begin(), pawn.end(), ti) == pawn.end() || ti == 32) + { + array tPawn = pawn; + tPawn[i] = ti; + if (diceIndex == 9) + { + ans = max(ans, score + board[ti][0]); + } + else + { + dfs(tPawn, diceIndex + 1, score + board[ti][0]); + } + } + } +} + +int main() +{ + ios::sync_with_stdio(false); + cin.tie(0); + cout.tie(0); + + for (int i = 0; i < 10; ++i) + { + cin >> dice[i]; + } + + array pawn = {0, 0, 0, 0}; + dfs(pawn, 0, 0); + cout << ans << endl; + + return 0; +} diff --git "a/\355\230\204\354\244\221/conveyor belt sushi, Immigration/2531 conveyor belt sushi.cpp" "b/\355\230\204\354\244\221/conveyor belt sushi, Immigration/2531 conveyor belt sushi.cpp" new file mode 100644 index 0000000..0d30797 --- /dev/null +++ "b/\355\230\204\354\244\221/conveyor belt sushi, Immigration/2531 conveyor belt sushi.cpp" @@ -0,0 +1,49 @@ +// 2531 conveyor belt sushi + +// 1. 연속해서 k개 접시먹을 경우 정액 +// 2. 처음과 끝이 연결되어 있기 때문에 %연산자를 사용하여 계속 돌게 +// 3. 초밥 종류 하나가 쓰인 쿠폰을 발행, 하나를 추가로 무료 제공, belt위에 없을 경우 새로 만들어줌 +// 4. 이미 먹은 초밥종류에 쿠폰이 포함되어 있으면 가짓수 늘리지 말기 +// 5. 먼저 쿠폰에 초밥을 먹었다 가정하고 최댓값을 측정하면 + +#include +#include +#include + +using namespace std; + +int n, d, k, c; // 접시수, 종류, 연속횟수, 쿠폰번호 +int susi[30001]; +int visited[30001]; // 이미 선택된 초밥? +int max_susi = 0; // 최대 가짓수 + +int main() +{ + cin >> n >> d >> k >> c; + + // 연속된 k개 접시 선택 + for (int i = 0; i < n; i++) + { + cin >> susi[i]; + } + + for (int i = 0; i < n; i++) + { + int flag = 0; // 중복된 초밥갯수를 세는 + int coupon = 1; // 가짓수에 포함되면 0, 아니면 1 + + for (int j = i; j < i + k; j++) + { + if (!visited[susi[j % n]] == 1) + visited[susi[j % n]] = true; + else + flag++; // 중복된 초밥 있음 + } + if (visited[c]) + coupon = 0; + max_susi = max(max_susi, k - flag + coupon); + memset(visited, false, sizeof(visited)); + } + cout << max_susi << endl; + return 0; +} \ No newline at end of file diff --git "a/\355\230\204\354\244\221/conveyor belt sushi, Immigration/Immigration(Programmers Binary Search).cpp" "b/\355\230\204\354\244\221/conveyor belt sushi, Immigration/Immigration(Programmers Binary Search).cpp" new file mode 100644 index 0000000..2ef89e0 --- /dev/null +++ "b/\355\230\204\354\244\221/conveyor belt sushi, Immigration/Immigration(Programmers Binary Search).cpp" @@ -0,0 +1,56 @@ +// Immigration(Programmers / Binary Search) + +// 입국자 1,2,3,4,5,6 +// 심사자 A(7분) :1 (7), 3 (14), 5 (21), 6 (28!!!) +// 심사자 B(10분) :2 (10)', 4 (20), 6 (30xxxx) + +// 근데 만약 심사가 끝나는 시간이 주어진다면??? 이분탐색으로!!! 최소시간 * 사람수 = 7분 * 6명 = 42분 +// 심사자 A(7분) : 15 / 7 = 최대 2명 +// 심사자 B(10분) : 15 / 10 = 최대 1명 + +#include +#include +#include + +using namespace std; + +int solution(int n, vector times) +{ + int start = 1; // 1분 + int end = *min_element(times.begin(), times.end()) * n; // 42분 + int answer = end; + + while (start <= end) + { + // 이분탐색 + int mid = (start + end) / 2; + int cnt = 0; + + // 중간값을 기준으로 최대 몇명을 심사? + cnt = 0; + + // 주어진시간 / 심사관의 심사시간 = 심사가능한 최대 인원 + for (int time : times) + { + cnt += mid / time; + } + // 심사할수있는 사람수 < 심사해야하는 사람 수 = 시간 더 필요 + if (cnt < n) + { + start = mid + 1; + } + else + end = mid - 1; + } + return start; +} + +int main() +{ + int n = 6; + vector times = {7, 10}; + + cout << solution(n, times) << endl; + + return 0; +} diff --git "a/\355\230\204\354\244\221/helloworld.txt" "b/\355\230\204\354\244\221/helloworld.txt" deleted file mode 100644 index bc7774a..0000000 --- "a/\355\230\204\354\244\221/helloworld.txt" +++ /dev/null @@ -1 +0,0 @@ -hello world! \ No newline at end of file diff --git "a/\355\230\204\354\244\221/n+1 game, parcel(programmers)/n+1 game.cpp" "b/\355\230\204\354\244\221/n+1 game, parcel(programmers)/n+1 game.cpp" new file mode 100644 index 0000000..bda7192 --- /dev/null +++ "b/\355\230\204\354\244\221/n+1 game, parcel(programmers)/n+1 game.cpp" @@ -0,0 +1,100 @@ +// 프로그래머스 n + 1 카드게임 + +#include +#include +#include +#include + + +using namespace std; + +int n =0; // 카드 갯수 + +int MyCardList[1001] = {0,}; // 배열의 index를 1부터 할거임 1~1000 +int CardsList[1001] = {0,}; // 내가 뽑을 수 있는 카드 리스트 + + +// 1. 코인을 소모하고 카드를 뽑는 함수(카드 적힌 수가 n+1) + +// 손에 들고있는 카드와 뽑지 않은 카드를 조합하여 n+1만들어주기 +int Get_Card(){ + + // 1장을 뽑아 n+1을 경우 + for(int i=0; i<=n; i++){ + // ex) 12까지 카드가 있다고 가정했을 때, 2 + (12+1-2) = 13 + if (MyCardList[i] == 1 && CardsList[n+1-i] == 1){ + MyCardList[i] =0; + CardsList[n+1-i] =0; + return 1; + } + } + // 뽑은 2장이 n+1인 경우 + for(int i=0; i<=n; i++){ + if (MyCardList[i] == 1 && CardsList[n+1-i] == 1){ + MyCardList[i] =0; + CardsList[n+1-i] =0; + return 2; + } + } + + // 합을 n+1을 만들 수 없는 경우 + return 0; +} + +// 2. 코인을 소모하지 않고 버리는 함수 + +// 손에 들고 있는 카드를 조합하여 n+1 찾아주기 +int Trash_Card(){ + + for(int i =1; i<=n; i++){ + if(MyCardList[i] ==1 && MyCardList[n+1-i] ==1){ + MyCardList[i] = 0; + MyCardList[n+1-i] = 0; + // n+1조건을 만족하는 첫번째 카드의 index(두번째는 자동으로 알 수 있음) + return i; + } + } + return 0; +} + + +// cards_len은 배열 cards의 길이입니다. +int Solution(int coin, vector cards) { + int answer = 0; + + n = cards.size(); + + int NowCount = n/3; + int temp = 0; + + // 뽑은 카드를 1처리 + for(int i=0; i < NowCount; i++){ + MyCardList[cards[i]] =1; + } + + // 라운드 진행 + for(int i = NowCount; i< NowCount; i++){ + answer += 1; + + //라운드별로 두장의 카드를 뽑고, 뽑을 카드를 저장 + CardsList[cards[i]] =1; + CardsList[cards[i+1]] =1; + + if(Trash_Card()){ + continue; + } + + // 손에 들고 있는 카드 + 뽑을카드 = n+1 후, 필요하다면 coins를 사용하여 조합을 만듦 + temp = Get_Card(); + + if(temp && coin >= temp){ + coin -= temp; + } + else { + return answer; + } + } + + + return answer; +} \ No newline at end of file diff --git "a/\355\230\204\354\244\221/n+1 game, parcel(programmers)/parcel.cpp" "b/\355\230\204\354\244\221/n+1 game, parcel(programmers)/parcel.cpp" new file mode 100644 index 0000000..47f599e --- /dev/null +++ "b/\355\230\204\354\244\221/n+1 game, parcel(programmers)/parcel.cpp" @@ -0,0 +1,60 @@ +// 백준_8980_택배 + +// 정보 +// 마을수, 트럭용량 +// 배송정보 수 + +// 접근법 +// 받는 마을을 기준으로 오름차순 정리(가까운 마을, 박스수가 작은거 부터) +// 각 구간별로 트럭에 실을 수 있는 최대 박스수 계산 + +#include +#include +#include + +using namespace std; + +int C, V; // City, Volume +int B; // Box + +// <<보내는 마을번호, 받는 마을번호>, 박스갯수> +vector , int>> list; + +int truck[2001]; // City별 truck에 싣고있는 택배수 저장 +int answer; // 최대 박스 수 + +bool compare(pair< pair,int >a, pair< pair,int >b){ + if(a.first.second == b.first.second) + return a.first.first < b.first.first; + else + return a.first.second < b.first.second; +} + +int main(){ + + cin >> C >> V; + cin >> B; + + // 배송정보를 받아 저장하고, 배송정보를 저장 + for(int i=0; i> send >> receive >> box; + + list.push_back({ {send, receive}, box }); // push_back(Vector의 마지막에 새로운 2차원배열을 추가하기 위해 임시 객체를 하나 만들어서 거기에 값을 복사 후, Vector에 삽입하는 과정) + } + sort(list.begin(), list.end(), compare); // 오름차순 + + // 배송정보 처리, 싣을 수 있는 최대 박스수 계산, 트럭 상태변수에 저장 + for(int i=0; i