├── .eslintrc.json ├── .gitattributes ├── .gitignore ├── .prettierrc ├── 10021.js ├── 10026.js ├── 10096.js ├── 1013.js ├── 10164.js ├── 1024.js ├── 1025.js ├── 1027.js ├── 1032.js ├── 1038.js ├── 10422.js ├── 10429 copy.js ├── 10429.js ├── 10431.js ├── 1049.js ├── 1057.js ├── 1058.js ├── 1068.js ├── 1072.js ├── 1075.js ├── 10775.js ├── 10800.js ├── 10800_v2.js ├── 10809.js ├── 10811.js ├── 10813.js ├── 10814.js ├── 10828.js ├── 10835.js ├── 10835_v2.js ├── 10845.js ├── 10917.js ├── 10942.js ├── 10950.js ├── 10986.js ├── 10994.js ├── 10997.js ├── 1100.js ├── 11005.js ├── 11021.js ├── 11022.js ├── 11048.js ├── 11057.js ├── 11058.js ├── 11058_v2.js ├── 1107.js ├── 11277.js ├── 11279.js ├── 11279_v2 copy.js ├── 11279_v2.js ├── 1135.js ├── 1138.js ├── 11382.js ├── 11383.js ├── 1138_v2.js ├── 11401.js ├── 11403.js ├── 11404.js ├── 1141.js ├── 11444.js ├── 11501.js ├── 11536.js ├── 11536_v2.js ├── 11559.js ├── 11568.js ├── 11654.js ├── 11657.js ├── 11660.js ├── 11663.js ├── 1167.js ├── 11720.js ├── 11723.js ├── 11723_v2.js ├── 11724.js ├── 11726.js ├── 1173.js ├── 1181.js ├── 1182.js ├── 1193.js ├── 11950.js ├── 11971.js ├── 1202.js ├── 12026.js ├── 1205.js ├── 12100.js ├── 1213.js ├── 1219.js ├── 1225.js ├── 1235.js ├── 1239.js ├── 1245.js ├── 1251.js ├── 1267.js ├── 1268.js ├── 12759.js ├── 12845.js ├── 12852.js ├── 12871.js ├── 1291.js ├── 12915.js ├── 1292.js ├── 12968.js ├── 12993.js ├── 1300.js ├── 13022.js ├── 1308.js ├── 1309.js ├── 13144.js ├── 13164.js ├── 13273.js ├── 13274.js ├── 13301.js ├── 13397.js ├── 13398.js ├── 1340.js ├── 13458.js ├── 13460.js ├── 13460_v2.js ├── 13496.js ├── 1351.js ├── 1351_v2.js ├── 13549.js ├── 13702.js ├── 1374.js ├── 1389.js ├── 1394.js ├── 14002.js ├── 14003.js ├── 1406.js ├── 1406_v2.js ├── 1411.js ├── 1417.js ├── 1421.js ├── 14218.js ├── 14219.js ├── 14226.js ├── 14226_v2.js ├── 14226_v3.js ├── 14232.js ├── 14235.js ├── 14235_v2.js ├── 1434.js ├── 14382.js ├── 1440.js ├── 14430.js ├── 1446.js ├── 14494.js ├── 14495.js ├── 14499.js ├── 14500.js ├── 14501.js ├── 14502.js ├── 14503.js ├── 1459.js ├── 14612.js ├── 14620.js ├── 14629.js ├── 1463.js ├── 14650.js ├── 14651.js ├── 14658.js ├── 14658_v2.js ├── 14658_v3.js ├── 14699.js ├── 14713.js ├── 14720.js ├── 14728.js ├── 1475.js ├── 14852.js ├── 14888.js ├── 14889.js ├── 14890.js ├── 14891.js ├── 14916.js ├── 14940.js ├── 1495.js ├── 1504.js ├── 1508.js ├── 1516.js ├── 15486.js ├── 15552.js ├── 15565.js ├── 15610.js ├── 15681.js ├── 15683.js ├── 15684.js ├── 15685.js ├── 15686.js ├── 15703.js ├── 15719.js ├── 15719_v2.js ├── 15719_v3.js ├── 15724.js ├── 15812.js ├── 15903.js ├── 15906.js ├── 15964.js ├── 15970.js ├── 1598.js ├── 15989.js ├── 15992.js ├── 15993.js ├── 16099.js ├── 16113.js ├── 16114.js ├── 16194.js ├── 16198.js ├── 16199.js ├── 16206.js ├── 16234.js ├── 16235.js ├── 16235_v2.js ├── 16235_v3.js ├── 16236.js ├── 16402.js ├── 16439.js ├── 1644.js ├── 16441.js ├── 16441_v2.js ├── 1644_v2.js ├── 16456.js ├── 16456_v2.js ├── 16501.js ├── 16502.js ├── 16564.js ├── 16568.js ├── 1660.js ├── 16614.js ├── 16637.js ├── 1674.js ├── 1678.js ├── 1689.js ├── 16918.js ├── 16928.js ├── 16948.js ├── 16955.js ├── 16956.js ├── 1697.js ├── 1700.js ├── 17070.js ├── 17070_v2.js ├── 17086.js ├── 17135.js ├── 17136.js ├── 17136_v2.js ├── 17136_v3.js ├── 17140.js ├── 17142.js ├── 17143.js ├── 17143_v2.js ├── 17143_v3.js ├── 17144.js ├── 17179.js ├── 17212.js ├── 17214.js ├── 17225.js ├── 17266.js ├── 1727.js ├── 1727_v2.js ├── 17281.js ├── 17281_v10.js ├── 17281_v11.js ├── 17281_v2.js ├── 17281_v3.js ├── 17281_v4.js ├── 17281_v5.js ├── 17281_v6.js ├── 17281_v7.js ├── 17281_v8.js ├── 17281_v9.js ├── 17297.js ├── 17299.js ├── 1730.js ├── 17393.js ├── 17406.js ├── 17413.js ├── 17420.js ├── 17420_v2.js ├── 17471.js ├── 17471_v2.js ├── 17472.js ├── 17478.js ├── 1748.js ├── 17484.js ├── 1753.js ├── 1758.js ├── 1759.js ├── 17626.js ├── 17626_v2.js ├── 1766.js ├── 1771.js ├── 1771_v2.js ├── 17779.js ├── 17779_v2.js ├── 1781.js ├── 17822.js ├── 17825.js ├── 17837.js ├── 1806.js ├── 1806_v2.js ├── 1811.js ├── 18115.js ├── 18198.js ├── 18228.js ├── 18229.js ├── 18398.js ├── 1863.js ├── 1865.js ├── 18768.js ├── 18870.js ├── 1889.js ├── 1911.js ├── 1914.js ├── 1918.js ├── 1919.js ├── 19236.js ├── 19237.js ├── 19238.js ├── 1924.js ├── 1927.js ├── 1927_v2.js ├── 1929.js ├── 1943.js ├── 1943_v2.js ├── 1943_v3.js ├── 1943_v4.js ├── 1943_v5.js ├── 19644.js ├── 19644_v2.js ├── 19699.js ├── 19844.js ├── 1987.js ├── 1987_v2.js ├── 20005.js ├── 20006.js ├── 20055.js ├── 20056.js ├── 20057.js ├── 20058.js ├── 20061.js ├── 2011.js ├── 20125.js ├── 20166.js ├── 20188.js ├── 20301.js ├── 20309.js ├── 20364.js ├── 20500.js ├── 20529.js ├── 20544.js ├── 20551.js ├── 2056.js ├── 2082.js ├── 2109.js ├── 2121.js ├── 2133.js ├── 2134.js ├── 2134_v2.js ├── 2136.js ├── 2143.js ├── 2143_v2.js ├── 2143_v3.js ├── 21555.js ├── 21557.js ├── 21608.js ├── 21609.js ├── 2161.js ├── 21610.js ├── 21611.js ├── 21611_v2.js ├── 2161_v2.js ├── 2167.js ├── 2169.js ├── 2174.js ├── 21758.js ├── 21773.js ├── 2179.js ├── 2179_v2.js ├── 2179_v3.js ├── 2179_v4.js ├── 2194.js ├── 21942.js ├── 21966.js ├── 2204.js ├── 2208.js ├── 22232.js ├── 2225.js ├── 22351.js ├── 2238.js ├── 2240.js ├── 22866.js ├── 22899.js ├── 2290.js ├── 2294.js ├── 22954.js ├── 22988.js ├── 22988_v2.js ├── 22988_v3.js ├── 2302.js ├── 23031.js ├── 2304.js ├── 2307.js ├── 2307_v2.js ├── 2307_v3.js ├── 23288.js ├── 23289.js ├── 23290.js ├── 23291.js ├── 23293.js ├── 23322.js ├── 23323.js ├── 23350.js ├── 2338.js ├── 23738.js ├── 23747.js ├── 23815.js ├── 23841.js ├── 23842.js ├── 23971.js ├── 24042.js ├── 2410.js ├── 2410_v2.js ├── 24183.js ├── 2420.js ├── 24228.js ├── 2428.js ├── 24337.js ├── 2438.js ├── 24418.js ├── 24418_v2.js ├── 24444.js ├── 24498.js ├── 24499.js ├── 24511.js ├── 2467.js ├── 2477.js ├── 24887.js ├── 24913.js ├── 2503.js ├── 2504.js ├── 25045.js ├── 25083.js ├── 25167.js ├── 25173.js ├── 25187.js ├── 25215.js ├── 2525.js ├── 25287.js ├── 2530.js ├── 25304.js ├── 2531.js ├── 25421.js ├── 25578.js ├── 2558.js ├── 2563.js ├── 25630.js ├── 25631.js ├── 25634.js ├── 25642.js ├── 25682.js ├── 25704.js ├── 25706.js ├── 25709.js ├── 2573.js ├── 25757.js ├── 2576.js ├── 2578.js ├── 2579.js ├── 2580.js ├── 2585.js ├── 2585_v2.js ├── 2589.js ├── 2591.js ├── 25915.js ├── 25916.js ├── 25917.js ├── 25918.js ├── 25921.js ├── 25966.js ├── 25972.js ├── 25991.js ├── 26069.js ├── 26152.js ├── 2616.js ├── 2616_v2.js ├── 2623.js ├── 2624.js ├── 2631.js ├── 2636.js ├── 2636_v2.js ├── 2637.js ├── 2638.js ├── 26495.js ├── 26530.js ├── 26575.js ├── 26596.js ├── 2666.js ├── 2668.js ├── 2675.js ├── 2685.js ├── 2685_v2.js ├── 2688.js ├── 2714.js ├── 27159.js ├── 27161.js ├── 27165.js ├── 27277.js ├── 27278.js ├── 27310.js ├── 27313.js ├── 27313_v2.js ├── 2738.js ├── 2740.js ├── 2742.js ├── 2744.js ├── 27465.js ├── 27466.js ├── 27466_v2.js ├── 2748.js ├── 27497.js ├── 27522.js ├── 27532.js ├── 2754.js ├── 27584.js ├── 2766.js ├── 27724.js ├── 2784.js ├── 27889.js ├── 27922.js ├── 27962._v2.js ├── 27962.js ├── 27964.js ├── 27964_v2.js ├── 27967.js ├── 27969.js ├── 2799.js ├── 28066.js ├── 28078.js ├── 28107.js ├── 28128.js ├── 28279.js ├── 28353.js ├── 28357.js ├── 28358.js ├── 28360.js ├── 28419.js ├── 28431.js ├── 28432.js ├── 28433.js ├── 28438.js ├── 28447.js ├── 2870.js ├── 29019.js ├── 2908.js ├── 2914.js ├── 2920.js ├── 29336.js ├── 2960.js ├── 29615.js ├── 29721.js ├── 29728.js ├── 29730.js ├── 29791.js ├── 29792.js ├── 29793.js ├── 29794.js ├── 29813.js ├── 30024.js ├── 30036.js ├── 30045.js ├── 3020.js ├── 3020_v2.js ├── 30403.js ├── 30404.js ├── 30446.js ├── 30460.js ├── 30461.js ├── 3054.js ├── 30544.js ├── 3060.js ├── 3060_v2.js ├── 3060_v3.js ├── 30679.js ├── 30802.js ├── 30803.js ├── 30804.js ├── 30805.js ├── 3085.js ├── 30890.js ├── 3096.js ├── 30980.js ├── 3107.js ├── 3109.js ├── 3109_v2.js ├── 31462.js ├── 31495.js ├── 31671.js ├── 31714.js ├── 31797.js ├── 31845.js ├── 31848.js ├── 3186.js ├── 3186_v2.js ├── 3190.js ├── 31937.js ├── 3254.js ├── 32622.js ├── 32654.js ├── 3273.js ├── 3372.js ├── 3665.js ├── 3699.js ├── 3758.js ├── 3787.js ├── 3954.js ├── 3954_v2.js ├── 3982.js ├── 3986.js ├── 4101.js ├── 4108.js ├── 4153.js ├── 4195.js ├── 4299.js ├── 4335.js ├── 4659.js ├── 4811.js ├── 4821.js ├── 4929.js ├── 4949.js ├── 5046.js ├── 5073.js ├── 5076.js ├── 5339.js ├── 5341.js ├── 5357.js ├── 5373.js ├── 5545.js ├── 5557.js ├── 5582.js ├── 5585.js ├── 5597.js ├── 5928.js ├── 6463.js ├── 6549.js ├── 6603.js ├── 6616.js ├── 6894.js ├── 6945.js ├── 7490.js ├── 7579.js ├── 7579_v2.js ├── 7579_v3.js ├── 7682.js ├── 7891.js ├── 8437.js ├── 8979.js ├── 8980.js ├── 8980_v2.js ├── 8983.js ├── 9012.js ├── 9017.js ├── 9017_v2.js ├── 9084.js ├── 9086.js ├── 9328.js ├── 9335.js ├── 9335_v2.js ├── 9335_v3.js ├── 9335_v4.js ├── 9370.js ├── 9370_v2.js ├── 9375.js ├── 9465.js ├── 9466.js ├── 9498.js ├── 9527.js ├── 9576.js ├── 9626.js ├── 9653.js ├── 9655.js ├── 9655_v2.js ├── 9655_v3.js ├── 9658.js ├── 9663.js ├── 9782.js ├── 9872.js ├── 9935.js ├── LICENSE ├── Readme.md ├── package-lock.json ├── package.json ├── solvedac-grand-arena-1 ├── A.js ├── B.js ├── C.js ├── E.js └── H.js └── solvedac-grand-arena-3 ├── A.js ├── B.js ├── C.js ├── D.js ├── E.js └── F.js /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true, 4 | "es2020": true 5 | }, 6 | "extends": [ 7 | "prettier", 8 | "airbnb-base", 9 | "plugin:prettier/recommended" 10 | ], 11 | "parserOptions": { 12 | "ecmaVersion": 2022 13 | }, 14 | "rules": { 15 | "prettier/prettier": ["error"], 16 | "linebreak-style": "off", 17 | "max-classes-per-file": "off", 18 | "no-console": "off", 19 | "no-shadow":"off", 20 | "lines-between-class-members": "off", 21 | "prefer-destructuring": "off", 22 | "no-continue": "off", 23 | "no-restricted-syntax": "off", 24 | "prefer-const": "off" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 27981.js 2 | 1038.js 3 | 1038_v2.js 4 | 27434.js 5 | 27965.js 6 | 7 | input 8 | 비밀/ 9 | 10 | node_modules/ -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "printWidth": 100, 4 | "endOfLine": "crlf" 5 | } 6 | -------------------------------------------------------------------------------- /1013.js: -------------------------------------------------------------------------------- 1 | const PATTERN = /^(?:100+1+|01)+$/; 2 | 3 | // input 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [_, ...testCases] = require('fs').readFileSync(INPUT_FILE).toString().trim() 6 | .split('\n'); 7 | 8 | // process 9 | const result = testCases.map((string) => (PATTERN.test(string) ? 'YES' : 'NO')); 10 | 11 | // output 12 | console.log(result.join('\n')); 13 | -------------------------------------------------------------------------------- /1024.js: -------------------------------------------------------------------------------- 1 | /* 2 | sum(i, i+1, i+2, ..., i+k-1) 3 | = i*k + k(k-1)/2 4 | = N 5 | k는 L 이상 100 이하 6 | k=L부터 100까지 돌면서 이 식을 만족하는 i가 있는지 찾기 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? 'dev/stdin' : './input'; 9 | const [sum, minLength] = require('fs') 10 | .readFileSync(INPUT_FILE) 11 | .toString() 12 | .trim() 13 | .split(' ') 14 | .map(Number); 15 | 16 | let length; 17 | let start = -1; 18 | 19 | for (length = minLength; length <= 100; length += 1) { 20 | const equation = sum - (length * (length - 1)) / 2; 21 | if (equation >= 0 && equation % length === 0) { 22 | start = equation / length; 23 | break; 24 | } 25 | } 26 | 27 | if (start === -1) { 28 | console.log(-1); 29 | } else { 30 | const sol = Array.from({ length }).map((_, idx) => start + idx); 31 | console.log(sol.join(' ')); 32 | } 33 | -------------------------------------------------------------------------------- /1032.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...files] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const pattern = []; 5 | 6 | for (let i = 0; i < files[0].length; i += 1) { 7 | if (files.every((file) => file[i] === files[0][i])) { 8 | pattern.push(files[0][i]); 9 | } else { 10 | pattern.push('?'); 11 | } 12 | } 13 | 14 | console.log(pattern.join('')); 15 | -------------------------------------------------------------------------------- /10431.js: -------------------------------------------------------------------------------- 1 | /* 2 | i번 학생: 처음~i-1번 학생들 중 본인보다 키가 큰애들을 밀어냄 3 | 단순히 초기상태에서 본인 앞에 본인보다 키큰애가 몇명인지 세는 문제. 4 | O(N^2)이지만 max(N)=20이라 충분히 가능. 5 | */ 6 | // functions 7 | const countMoves = function countTotalMovesCallback(prevMoves, curHeight, index, heights) { 8 | let moves = 0; 9 | 10 | for (let i = 0; i < index; i += 1) { 11 | if (heights[i] > curHeight) moves += 1; 12 | } 13 | 14 | return prevMoves + moves; 15 | }; 16 | 17 | // input 18 | const inputFile = process.platform === 'linux' ? '/dev/stdin' : './input'; 19 | const [P, ...tests] = require('fs').readFileSync(inputFile).toString().trim() 20 | .split('\n') 21 | .map((line) => line.split(' ').map(Number)); 22 | 23 | // process 24 | const sol = []; 25 | tests.forEach((test) => { 26 | const [caseNo, ...heights] = test; 27 | const moveCnt = heights.reduce(countMoves, 0); 28 | sol.push(`${caseNo} ${moveCnt}`); 29 | }); 30 | 31 | // output 32 | console.log(sol.join('\n')); 33 | -------------------------------------------------------------------------------- /1049.js: -------------------------------------------------------------------------------- 1 | /* 2 | 제일 싼 여섯 개 패키지 가격 3 | 제일 싼 낱개 패키지 가격 4 | 5 | 이거 두 개 구해서 계산하기 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const [[lineCount], ...prices] = require('fs') 9 | .readFileSync(INPUT_FILE) 10 | .toString() 11 | .trim() 12 | .split('\n') 13 | .map((line) => line.split(' ').map(Number)); 14 | 15 | const { minPackagePrice, minSinglePrice } = prices.reduce( 16 | ({ minPackagePrice, minSinglePrice }, [packagePrice, singlePrice]) => ({ 17 | minPackagePrice: Math.min(packagePrice, minPackagePrice), 18 | minSinglePrice: Math.min(singlePrice, minSinglePrice), 19 | }), 20 | { minPackagePrice: Infinity, minSinglePrice: Infinity }, 21 | ); 22 | 23 | const packagePrice = Math.min(minPackagePrice, minSinglePrice * 6); 24 | 25 | const sol = 26 | Math.min(minPackagePrice, (lineCount % 6) * minSinglePrice) + 27 | Math.floor(lineCount / 6) * packagePrice; 28 | 29 | console.log(sol); 30 | -------------------------------------------------------------------------------- /1057.js: -------------------------------------------------------------------------------- 1 | /* 2 | 만나는 경우 3 | 두 사람의 번호 차가 1이고 둘 중 작은 번호가 홀수일 때 4 | 5 | 다음 번호 6 | 홀수면 1 더해서 나누기 2 7 | 짝수면 나누기 2 8 | 9 | 대결하지 않는 경우 10 | 가 있나? 11 | */ 12 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 13 | let [, jimin, hansoo] = require('fs').readFileSync(INPUT_FILE).toString().trim() 14 | .split(' ') 15 | .map(Number); 16 | 17 | const getNextRoundEntryNumber = (value) => (value % 2 === 0 ? value / 2 : (value + 1) / 2); 18 | 19 | let round; 20 | for ( 21 | round = 1; 22 | Math.abs(jimin - hansoo) !== 1 || Math.min(jimin, hansoo) % 2 !== 1; 23 | round += 1 24 | ) { 25 | jimin = getNextRoundEntryNumber(jimin); 26 | hansoo = getNextRoundEntryNumber(hansoo); 27 | } 28 | 29 | console.log(round); 30 | -------------------------------------------------------------------------------- /1072.js: -------------------------------------------------------------------------------- 1 | /* 2 | 현재 승률이 100%면 절대 승률이 변하지 않음 3 | 현재 승률이 99%면 절대 승률을 100%으로 만들 수 없음(버림이니까) 4 | 판수를 늘릴수록 승률이 오름 5 | 6 | (Y+k)/(X+k) > Y/X 7 | 가 되는 첫 k를 구하는 문제 8 | 9 | 이분탐색으로 가시죠 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [totalCount, winCount] = require('fs') 13 | .readFileSync(INPUT_FILE) 14 | .toString() 15 | .trim() 16 | .split(' ') 17 | .map(Number); 18 | 19 | const winRate = totalCount > 0 ? Math.floor((winCount * 100) / totalCount) : 0; 20 | const getWinRate = (newGameCount) => 21 | Math.floor(((winCount + newGameCount) * 100) / (totalCount + newGameCount)); 22 | 23 | let sol = -1; 24 | 25 | if (winRate < 99) { 26 | let left = 1; 27 | let right = totalCount === 0 ? 2 : totalCount; 28 | 29 | while (left < right) { 30 | const mid = Math.floor((left + right) / 2); 31 | if (getWinRate(mid) > winRate) right = mid; 32 | else left = mid + 1; 33 | } 34 | 35 | sol = left; 36 | } 37 | 38 | console.log(sol); 39 | -------------------------------------------------------------------------------- /1075.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [value, dividend] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map(Number); 5 | 6 | const start = Math.floor(value / 100) * 100; 7 | let lastTwoNumbers = 0; 8 | 9 | for ( 10 | lastTwoNumbers = 0; 11 | (start + lastTwoNumbers) % dividend !== 0; 12 | lastTwoNumbers += 1 13 | ) {} 14 | 15 | console.log(lastTwoNumbers.toString().padStart(2, '0')); 16 | -------------------------------------------------------------------------------- /10809.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const word = require('fs').readFileSync(INPUT_FILE).toString().trim(); 3 | 4 | const smallACode = 'a'.charCodeAt(0); 5 | const sol = new Array(26).fill(-1); 6 | for (let index = 0; index < word.length; index += 1) { 7 | const alphabet = word.charCodeAt(index) - smallACode; 8 | if (sol[alphabet] === -1) sol[alphabet] = index; 9 | } 10 | 11 | console.log(sol.join(' ')); 12 | -------------------------------------------------------------------------------- /10811.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[basketCount], ...operations] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map((value) => Number(value) - 1)); 8 | 9 | let baskets = Array.from({ length: basketCount + 1 }).map((_, index) => index + 1); 10 | 11 | operations.forEach(([start, end]) => { 12 | baskets = [ 13 | ...baskets.slice(0, start), 14 | ...baskets.slice(start, end + 1).reverse(), 15 | ...baskets.slice(end + 1), 16 | ]; 17 | }); 18 | 19 | console.log(baskets.join(' ')); 20 | -------------------------------------------------------------------------------- /10813.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[basketCount], ...operations] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const baskets = Array.from({ length: basketCount + 1 }).map((_, index) => index); 10 | 11 | operations.forEach(([one, another]) => { 12 | const temp = baskets[one]; 13 | baskets[one] = baskets[another]; 14 | baskets[another] = temp; 15 | }); 16 | 17 | console.log(baskets.slice(1).join(' ')); 18 | -------------------------------------------------------------------------------- /10814.js: -------------------------------------------------------------------------------- 1 | class Member { 2 | constructor(name, age, index) { 3 | this.name = name; 4 | this.age = age; 5 | this.index = index; 6 | } 7 | } 8 | 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const members = require('fs').readFileSync(INPUT_FILE).toString().trim() 11 | .split('\n') 12 | .slice(1) 13 | .map((line, index) => { 14 | const [age, name] = line.split(' '); 15 | return new Member(name, Number(age), index); 16 | }); 17 | 18 | members.sort((a, b) => { 19 | if (a.age !== b.age) return a.age - b.age; 20 | return a.index - b.index; 21 | }); 22 | 23 | console.log(members.map((member) => `${member.age} ${member.name}`).join('\n')); 24 | -------------------------------------------------------------------------------- /10828.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...commands] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ')); 8 | 9 | const stack = []; 10 | const sol = []; 11 | 12 | commands.forEach(([command, value]) => { 13 | switch (command) { 14 | case 'push': 15 | stack.push(value); 16 | break; 17 | case 'pop': 18 | if (stack.length) sol.push(stack.pop()); 19 | else sol.push(-1); 20 | break; 21 | case 'size': 22 | sol.push(stack.length); 23 | break; 24 | case 'empty': 25 | sol.push(stack.length ? 0 : 1); 26 | break; 27 | case 'top': 28 | sol.push(stack.length ? stack[stack.length - 1] : -1); 29 | break; 30 | default: 31 | } 32 | }); 33 | 34 | console.log(sol.join('\n')); 35 | -------------------------------------------------------------------------------- /10950.js: -------------------------------------------------------------------------------- 1 | const inputFile = '/dev/stdin'; 2 | const input = require("fs").readFileSync(inputFile).toString().trim().split(/\s/); 3 | 4 | let T = parseInt(input[0]); 5 | let idx = 1; 6 | 7 | while (T > 0) 8 | { 9 | let val1 = parseInt(input[idx++]); 10 | let val2 = parseInt(input[idx++]); 11 | console.log(val1 + val2); 12 | T--; 13 | } -------------------------------------------------------------------------------- /10986.js: -------------------------------------------------------------------------------- 1 | /* 2 | A의 누적합 배열을 구한다. 3 | 누적합 배열의 두 원소 i와 j에 대해서 i%M = j%M 이면 된다. 4 | */ 5 | 6 | // input 7 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 8 | const [N, M, ... A] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(Number); 9 | 10 | // process 11 | prefix_sum = new Array(N); 12 | remainder_cnt = new Array(M).fill(0); 13 | 14 | prefix_sum[0] = A[0]; 15 | remainder_cnt[0]++; 16 | remainder_cnt[prefix_sum[0] % M]++; 17 | 18 | for (let i=1; i new Array(1 + 4 * (size - 1)).fill(' '), 7 | ); 8 | 9 | const fill = (start, length) => { 10 | if (length === 1) { 11 | board[start][start] = '*'; 12 | return; 13 | } 14 | 15 | for (let i = 0; i < length; i += 1) { 16 | board[start][start + i] = '*'; 17 | board[start + i][start] = '*'; 18 | board[start + length - 1][start + i] = '*'; 19 | board[start + i][start + length - 1] = '*'; 20 | } 21 | 22 | fill(start + 2, length - 4); 23 | }; 24 | 25 | fill(0, board.length); 26 | 27 | console.log(board.map((row) => row.join('')).join('\n')); 28 | -------------------------------------------------------------------------------- /1100.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const board = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | let count = 0; 5 | 6 | for (let row = 0; row < 8; row += 2) { 7 | for (let col = 0; col < 8; col += 2) { 8 | if (board[row][col] === 'F') count += 1; 9 | } 10 | } 11 | 12 | for (let row = 1; row < 8; row += 2) { 13 | for (let col = 1; col < 8; col += 2) { 14 | if (board[row][col] === 'F') count += 1; 15 | } 16 | } 17 | 18 | console.log(count); 19 | -------------------------------------------------------------------------------- /11005.js: -------------------------------------------------------------------------------- 1 | /* 2 | B진법으로 몇 자리 숫자인지를 찾는다 3 | 그다음에 나눗셈 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [value, base] = require('fs').readFileSync(INPUT_FILE).toString().trim() 7 | .split(' ') 8 | .map(Number); 9 | 10 | const digits = []; 11 | 12 | for (let digit = 1; digit <= value; digit *= base) { 13 | digits.push(digit); 14 | } 15 | 16 | const change = []; 17 | let remainder = value; 18 | 19 | while (digits.length) { 20 | const dividend = digits.pop(); 21 | 22 | const quotient = Math.floor(remainder / dividend); 23 | remainder %= dividend; 24 | 25 | change.push(quotient); 26 | } 27 | 28 | const sol = change.map((value) => ( 29 | value < 10 30 | ? value 31 | : String.fromCharCode(value - 10 + 'A'.charCodeAt(0)) 32 | )); 33 | 34 | console.log(sol.join('')); 35 | -------------------------------------------------------------------------------- /11021.js: -------------------------------------------------------------------------------- 1 | // input 2 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 3 | const testCases = require('fs').readFileSync(INPUT_FILE).toString().trim() 4 | .split('\n') 5 | .slice(1) 6 | .map((line) => line.split(' ').map(Number)); 7 | 8 | // process 9 | const sol = []; 10 | testCases.forEach(([A, B], index) => { 11 | sol.push(`Case #${index + 1}: ${A + B}`); 12 | }); 13 | 14 | // output 15 | console.log(sol.join('\n')); 16 | -------------------------------------------------------------------------------- /11022.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const testCases = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .slice(1) 5 | .map((line) => line.split(' ').map(Number)); 6 | 7 | const sol = []; 8 | testCases.forEach(([A, B], index) => { 9 | sol.push(`Case #${index + 1}: ${A} + ${B} = ${A + B}`); 10 | }); 11 | 12 | console.log(sol.join('\n')); 13 | -------------------------------------------------------------------------------- /11048.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(r, c) := (1,1)~(r,c)에서 모은 최대 사탕 개수 3 | opt(r, c) = 4 | opt(r-1, c) 5 | opt(r, c-1) 6 | opt(r-1, c-1) 7 | 셋 중 큰 값에 (r,c)의 사탕 개수를 더한 값. 8 | */ 9 | 10 | // input 11 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 12 | const input = require('fs').readFileSync(inputFile).toString().trim().split('\n'); 13 | 14 | const [row, col] = input[0].split(' ').map(x => parseInt(x)); 15 | let maze = []; 16 | for(let i=1; i<=row; i++) 17 | maze.push(input[i].split(' ').map(x => parseInt(x))); 18 | 19 | // process 20 | for(let r=0; r 0? maze[r - 1][c] : 0; 25 | let val2 = c > 0? maze[r][c - 1] : 0; 26 | let val3 = r > 0 && c > 0? maze[r - 1][c - 1] : 0; 27 | maze[r][c] += Math.max(val1, val2, val3); 28 | } 29 | } 30 | 31 | // output 32 | console.log(maze[row - 1][col - 1]); -------------------------------------------------------------------------------- /11057.js: -------------------------------------------------------------------------------- 1 | /* 2 | 일의 자리 수가 4면 그 뒤에 4, 5, 6, 7, 8, 9를 붙여서 길이 늘릴 수 있음. 3 | 4 | opt(i, j) := 길이가 i인 오르막 수 중 일의 자리가 j인 수의 개수 5 | 6 | opt(i, j) = 7 | sum( opt(i-1, k) ) 8 | k는 k <= j 인 자연수들 9 | */ 10 | 11 | // input 12 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 13 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 14 | 15 | // process 16 | let opt = [[], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]; 17 | 18 | for(let i=2; i<=N; i++) 19 | { 20 | let cur = [0]; 21 | for(let j=1; j<=9; j++) 22 | { 23 | let val = 0; 24 | for(let k=1; k<=j; k++) 25 | val += opt[i - 1][k]; 26 | cur.push(val % 10007); 27 | } 28 | opt.push(cur); 29 | } 30 | 31 | // output 32 | let sol = 0; 33 | for (line of opt) 34 | sol += line.reduce((prev, cur) => (prev + cur) % 10007, 0); 35 | sol %= 10007; 36 | console.log(sol); -------------------------------------------------------------------------------- /11058_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 연산횟수 i번일 때 최대 개수 3 | opt(i) = 4 | i (그냥 A를 i번 넣었음) 5 | opt(k) * (i-k-2) (단, k line.split(' ').map(Number)); 11 | 12 | const toBooleanArray = (value) => { 13 | return Array.from(value.toString(2).padStart(variableCount, '0')).map((val) => val === '1'); 14 | }; 15 | const isTrue = (status) => { 16 | return clauses.every(([a, b]) => { 17 | return (a > 0 ? status[a - 1] : !status[-a - 1]) || (b > 0 ? status[b - 1] : !status[-b - 1]); 18 | }); 19 | }; 20 | const canBeTrue = () => { 21 | for (let i = 0; i < 2 ** variableCount; i += 1) { 22 | const testCase = toBooleanArray(i); 23 | const result = isTrue(testCase); 24 | if (result) { 25 | return true; 26 | } 27 | } 28 | return false; 29 | }; 30 | 31 | console.log(canBeTrue() ? 1 : 0); 32 | -------------------------------------------------------------------------------- /1138.js: -------------------------------------------------------------------------------- 1 | /* 2 | 큰 숫자부터 배열에 배치한다. 3 | 본인 앞에 본인보다 큰 i명이 있다고 치면 배열[i] 에 넣으면 된다. 4 | max(N)=10이라 배열에 넣을 때의 시간 복잡도 최적화할 필요 X 5 | */ 6 | // input 7 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 8 | const [N, ...tallerThanMe] = require('fs').readFileSync(inputFile).toString().trim() 9 | .split(/\s/) 10 | .map(Number); 11 | 12 | // process 13 | const order = tallerThanMe.reduceRight( 14 | (prevArray, number, index) => ( 15 | [...prevArray.slice(0, number), index + 1, ...prevArray.slice(number)] 16 | ), 17 | [undefined], 18 | ); 19 | order.pop(); 20 | 21 | // output 22 | console.log(order.join(' ')); 23 | -------------------------------------------------------------------------------- /11382.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [A, B, C] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(' ') 4 | .map(Number); 5 | 6 | console.log(A + B + C); 7 | -------------------------------------------------------------------------------- /11383.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [info, ...images] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const [height] = info.split(' ').map(Number); 5 | const toLongString = (target) => { 6 | const result = []; 7 | Array.from(target).forEach((char) => { 8 | result.push(char, char); 9 | }); 10 | return result.join(''); 11 | }; 12 | 13 | let isEyfa = true; 14 | 15 | for (let i = 0; i < height; i += 1) { 16 | if (toLongString(images[i]) !== images[i + height]) { 17 | isEyfa = false; 18 | break; 19 | } 20 | } 21 | 22 | console.log(isEyfa ? 'Eyfa' : 'Not Eyfa'); 23 | -------------------------------------------------------------------------------- /1138_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 큰 숫자부터 배열에 배치한다. 3 | 본인 앞에 본인보다 큰 i명이 있다고 치면 배열[i] 에 넣으면 된다. 4 | max(N)=10이라 배열에 넣을 때의 시간 복잡도 최적화할 필요 X 5 | */ 6 | // input 7 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 8 | const [N, ...tallerThanMe] = require('fs').readFileSync(inputFile).toString().trim() 9 | .split(/\s/) 10 | .map(Number); 11 | 12 | // process 13 | const order = tallerThanMe.reduceRight( 14 | (prevArray, number, index) => { 15 | prevArray.splice(number, 0, index + 1); 16 | return prevArray; 17 | }, 18 | [undefined], 19 | ); 20 | order.pop(); 21 | 22 | // output 23 | console.log(order.join(' ')); 24 | -------------------------------------------------------------------------------- /11403.js: -------------------------------------------------------------------------------- 1 | /* 2 | 플로이드-워셜 3 | 근데 비용은 따지지 않는 4 | opt(a, b):= a에서 b로 가는 길이 있는지 5 | opt(a, b) = opt(a, b) or (opt(a, k) and opt(k, b)) 6 | 단, k는 a와 b가 아닌 임의의 점 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [[vertexCount], ...adjMatrix] = require('fs') 10 | .readFileSync(INPUT_FILE) 11 | .toString() 12 | .trim() 13 | .split('\n') 14 | .map((line) => line.split(' ').map(Number)); 15 | 16 | const opt = Array.from({ length: vertexCount }, (_, row) => 17 | Array.from({ length: vertexCount }, (_, col) => adjMatrix[row][col]), 18 | ); 19 | 20 | for (let mid = 0; mid < vertexCount; mid += 1) { 21 | for (let start = 0; start < vertexCount; start += 1) { 22 | for (let end = 0; end < vertexCount; end += 1) { 23 | opt[start][end] ||= opt[start][mid] && opt[mid][end]; 24 | } 25 | } 26 | } 27 | 28 | console.log(opt.map((row) => row.join(' ')).join('\n')); 29 | -------------------------------------------------------------------------------- /1141.js: -------------------------------------------------------------------------------- 1 | /* 2 | h 3 | | \ 4 | i ello 5 | 6 | r 7 | | \ 8 | un erun 9 | | 10 | ning 11 | 12 | 이런식으로 트리를 구성 13 | 이파리 개수를 센다. 14 | */ 15 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 16 | const [_, ...words] = require('fs').readFileSync(INPUT_FILE).toString().trim() 17 | .split('\n'); 18 | 19 | const tree = {}; 20 | 21 | const makeTree = (word) => { 22 | let root = tree; 23 | 24 | for (let i = 0; i < word.length; i += 1) { 25 | const char = word[i]; 26 | 27 | if (!root[char]) root[char] = {}; 28 | 29 | root = root[char]; 30 | } 31 | }; 32 | 33 | words.forEach((word) => makeTree(word)); 34 | 35 | let leafCount = 0; 36 | 37 | const dfs = (root) => { 38 | if (Object.keys(root).length === 0) { 39 | leafCount += 1; 40 | return; 41 | } 42 | 43 | Object.values(root).forEach((child) => dfs(child)); 44 | }; 45 | 46 | Object.values(tree).forEach((root) => dfs(root)); 47 | 48 | console.log(leafCount); 49 | -------------------------------------------------------------------------------- /11536.js: -------------------------------------------------------------------------------- 1 | // 런타임 에러 eacces 2 | 3 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 4 | const [N, ...names] = require('fs').readFileSync(INPUT_FILE).toString().trim() 5 | .split('\n'); 6 | 7 | const isIncreasing = names.every((name, index) => { 8 | if (index === 0) return true; 9 | 10 | return names[index - 1] < name; 11 | }); 12 | 13 | const isDecreasing = names.every((name, index) => { 14 | if (index === 0) return true; 15 | 16 | return names[index - 1] > name; 17 | }); 18 | 19 | if (isIncreasing) console.log('INCREASING'); 20 | else if (isDecreasing) console.log('DECREASING'); 21 | else console.log('NEITHER'); 22 | -------------------------------------------------------------------------------- /11536_v2.js: -------------------------------------------------------------------------------- 1 | const rl = require('readline').createInterface({ 2 | input: process.stdin, 3 | output: process.stdout, 4 | }); 5 | 6 | const isIncreasing = (names) => names.every((name, index) => { 7 | if (index === 0) return true; 8 | 9 | return names[index - 1] < name; 10 | }); 11 | 12 | const isDecreasing = (names) => names.every((name, index) => { 13 | if (index === 0) return true; 14 | 15 | return names[index - 1] > name; 16 | }); 17 | 18 | const solve = (names) => { 19 | if (isIncreasing(names)) console.log('INCREASING'); 20 | else if (isDecreasing(names)) console.log('DECREASING'); 21 | else console.log('NEITHER'); 22 | }; 23 | 24 | let isFirstLine = true; 25 | const names = []; 26 | 27 | rl.on('line', (line) => { 28 | if (isFirstLine) { 29 | isFirstLine = !isFirstLine; 30 | return; 31 | } 32 | names.push(line.trim()); 33 | }).on('close', () => { 34 | solve(names); 35 | }); 36 | -------------------------------------------------------------------------------- /11568.js: -------------------------------------------------------------------------------- 1 | /* 2 | 가장 긴 증가하는 부분 수열 문제. 3 | opt(i)를 제시한 카드들 중 앞에서 i개 중 가장~수열의 길이라 하면 4 | opt(i) = 5 | max(opt(j)) + 1 6 | 이때 j는 j parseInt(x)); 12 | const [N, ... card] = input; 13 | 14 | // process 15 | let sol = 1; 16 | let opt = [1]; 17 | 18 | for(let i=1; i prev + cur, 0); 7 | 8 | console.log(sol); 9 | -------------------------------------------------------------------------------- /11726.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 2*i 크기의 직사각형을 채우는 방법의 수 3 | opt(i) = opt(i-1) + opt(i-2) 4 | i-1까지 채우고 세로로 하나(|) 놓거나 5 | i-2까지 채우고 가로로 둘(=) 놓거나 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const size = Number(require('fs').readFileSync(INPUT_FILE).toString()); 9 | 10 | const DIVISOR = 10007; 11 | const cases = [1, 1]; 12 | 13 | for (let i = 2; i <= size; i += 1) { 14 | cases.push((cases[i - 1] + cases[i - 2]) % DIVISOR); 15 | } 16 | 17 | console.log(cases[size]); 18 | -------------------------------------------------------------------------------- /1173.js: -------------------------------------------------------------------------------- 1 | /* 2 | 일단 최대맥박까지 운동한다 3 | 1분 운동할만큼 쉬고 1분 운동 반복 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [targetTime, min, max, increase, decrease] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split(' ') 11 | .map(Number); 12 | 13 | let time; 14 | let exerciseTime = 0; 15 | let heartbeat = min; 16 | 17 | for (time = 0; exerciseTime < targetTime; time += 1) { 18 | if (min + increase > max) break; 19 | if (heartbeat + increase <= max) { 20 | heartbeat += increase; 21 | exerciseTime += 1; 22 | } else { 23 | heartbeat = Math.max(min, heartbeat - decrease); 24 | } 25 | } 26 | 27 | console.log(exerciseTime === targetTime ? time : -1); 28 | -------------------------------------------------------------------------------- /1181.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [N, ...words] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n'); 4 | 5 | const wordSet = Array.from(new Set(words)); 6 | 7 | wordSet.sort((a, b) => { 8 | if (a.length !== b.length) return a.length - b.length; 9 | if (a < b) return -1; 10 | if (a > b) return 1; 11 | return 0; 12 | }); 13 | 14 | console.log(wordSet.join('\n')); 15 | -------------------------------------------------------------------------------- /1182.js: -------------------------------------------------------------------------------- 1 | /* 2 | 백트래킹 3 | 재귀 직후에 S인지 검사 4 | 아니면 추가 재귀 5 | */ 6 | 7 | // input 8 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 9 | const [N, S, ... seq] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(Number); 10 | 11 | // process 12 | let count = 0; 13 | let visited = new Array(N); 14 | 15 | find_subseq_sum(0, 0, 0); 16 | 17 | // output 18 | console.log(count); 19 | 20 | // function 21 | function find_subseq_sum(current_index, current_sum, depth) 22 | { 23 | if (depth > 0 && current_sum === S) 24 | count++; 25 | 26 | if (depth === N) return; 27 | 28 | for (let i=current_index; i= X || X > (n * (n + 1)) / 2) { 12 | n += 1; 13 | } 14 | 15 | const index = X - ((n - 1) * n) / 2; 16 | 17 | if (n % 2 === 1) { 18 | console.log(`${n + 1 - index}/${index}`); 19 | } else { 20 | console.log(`${index}/${n + 1 - index}`); 21 | } 22 | -------------------------------------------------------------------------------- /11971.js: -------------------------------------------------------------------------------- 1 | /* 2 | 도로 길이가 100km밖에 안되니까 100칸짜리 배열로 처리 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const inputs = require('fs').readFileSync(INPUT_FILE).toString().trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const [roadSectionCount] = inputs[0]; 10 | const roadSections = inputs.slice(1, roadSectionCount + 1); 11 | const carSections = inputs.slice(roadSectionCount + 1); 12 | 13 | const road = []; 14 | roadSections.forEach(([length, speedLimit]) => road.push(...new Array(length).fill(speedLimit))); 15 | 16 | const carSpeed = []; 17 | carSections.forEach(([length, speed]) => carSpeed.push(...new Array(length).fill(speed))); 18 | 19 | const speedDifference = carSpeed.map((value, index) => value - road[index]); 20 | 21 | console.log(Math.max(0, ...speedDifference)); 22 | -------------------------------------------------------------------------------- /12026.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := i번 보도블록까지 오는 에너지 최솟값 3 | block(i) := i번 보도블록에 쓰여 있는 글자 4 | 5 | 만약 block(i)=O 라고 하면 6 | opt(i) = min(opt(j) + (i-j)^2) 7 | j는 j { 22 | if (score !== currentRankScore) { 23 | currentRank = index + 1; 24 | currentRankScore = score; 25 | } 26 | }); 27 | sol = currentRank; 28 | } 29 | 30 | // output 31 | console.log(sol); 32 | -------------------------------------------------------------------------------- /1225.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [one, another] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split(' ') 7 | .map((value) => [...value]); 8 | 9 | let sol = 0; 10 | 11 | one.forEach((oneValue) => { 12 | another.forEach((anotherValue) => { 13 | sol += Number(oneValue) * Number(anotherValue); 14 | }); 15 | }); 16 | 17 | console.log(sol); 18 | -------------------------------------------------------------------------------- /1235.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...numbers] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | let sol; 5 | for (let length = 1; length <= numbers[0].length; length += 1) { 6 | if (new Set(numbers.map((number) => number.slice(-length))).size === numbers.length) { 7 | sol = length; 8 | break; 9 | } 10 | } 11 | 12 | console.log(sol); 13 | -------------------------------------------------------------------------------- /1251.js: -------------------------------------------------------------------------------- 1 | /* 2 | 최대 50개의 글자 중 쪼개는 기준점이 될 두 곳을 고르는 경우의 수 3 | >> 2500보다 적음 4 | >> 완전탐색 가능 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const word = require('fs').readFileSync(INPUT_FILE).toString().trim() 8 | .split(''); 9 | 10 | let sol = 'z'.repeat(50); 11 | 12 | for (let divPoint1 = 1; divPoint1 < word.length - 1; divPoint1 += 1) { 13 | for (let divPoint2 = divPoint1 + 1; divPoint2 < word.length; divPoint2 += 1) { 14 | const newWord = [ 15 | word.slice(0, divPoint1).reverse().join(''), 16 | word.slice(divPoint1, divPoint2).reverse().join(''), 17 | word.slice(divPoint2).reverse().join(''), 18 | ].join(''); 19 | 20 | if (newWord < sol) sol = newWord; 21 | } 22 | } 23 | 24 | console.log(sol); 25 | -------------------------------------------------------------------------------- /1267.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...times] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split(/\s/) 7 | .map(Number); 8 | 9 | const getYPrice = (time) => Math.ceil((time + 1) / 30) * 10; 10 | const getMPrice = (time) => Math.ceil((time + 1) / 60) * 15; 11 | 12 | const yPrice = times.reduce((prev, time) => prev + getYPrice(time), 0); 13 | const mPrice = times.reduce((prev, time) => prev + getMPrice(time), 0); 14 | 15 | if (yPrice === mPrice) { 16 | console.log(`Y M ${yPrice}`); 17 | } else if (yPrice > mPrice) { 18 | console.log(`M ${mPrice}`); 19 | } else { 20 | console.log(`Y ${yPrice}`); 21 | } 22 | -------------------------------------------------------------------------------- /1268.js: -------------------------------------------------------------------------------- 1 | /* 2 | 학년별로 각 반의 인원수를 셈 3 | 학생별로 같은 반인 학생의 수를 구함 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[studentCount], ...students] = require('fs').readFileSync(INPUT_FILE).toString().trim() 7 | .split('\n') 8 | .map((line) => line.split(' ').map(Number)); 9 | 10 | let maxCount = 0; 11 | let maxStudent; 12 | 13 | for (let student = 0; student < studentCount; student += 1) { 14 | const sameClassStudents = new Set(); 15 | 16 | for (let grade = 0; grade < 5; grade += 1) { 17 | for (let otherStudent = 0; otherStudent < studentCount; otherStudent += 1) { 18 | if (students[student][grade] === students[otherStudent][grade]) { 19 | sameClassStudents.add(otherStudent); 20 | } 21 | } 22 | } 23 | 24 | if (sameClassStudents.size > maxCount) { 25 | maxCount = sameClassStudents.size; 26 | maxStudent = student + 1; 27 | } 28 | } 29 | 30 | console.log(maxStudent); 31 | -------------------------------------------------------------------------------- /12845.js: -------------------------------------------------------------------------------- 1 | /* 2 | 카드 합성 시 하나가 살고 하나가 죽음 3 | 죽는 카드는 최종 골드에 한 번만 기여를 할 수 있음 4 | 죽지 않는 카드는 최종 골드에 여러 번 기여할 수 있음 5 | 가장 레벨이 높은 카드를 계속 살리면 이득 6 | -> 가장 레벨이 높은 카드가 본인 옆에거를 마지막까지 잡아먹으면 됨 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [cardCount, ...cards] = require('fs') 10 | .readFileSync(INPUT_FILE) 11 | .toString() 12 | .trim() 13 | .split(/\s/) 14 | .map(Number); 15 | 16 | const max = Math.max(...cards); 17 | const sum = cards.reduce((sum, cur) => sum + cur, 0); 18 | const sol = sum - max + max * (cardCount - 1); 19 | 20 | console.log(sol); 21 | -------------------------------------------------------------------------------- /12871.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [s, t] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const isSame = s.repeat(t.length) === t.repeat(s.length); 5 | 6 | console.log(isSame ? 1 : 0); 7 | -------------------------------------------------------------------------------- /1292.js: -------------------------------------------------------------------------------- 1 | /* 2 | 부분합 문제. 3 | 처음~X 까지의 합을 구하는 함수를 만들면 끝. 4 | */ 5 | 6 | // input 7 | const inputFile = process.platform ==='linux' ? '/dev/stdin' : './input'; 8 | const input = require('fs').readFileSync(inputFile).toString().trim().split(' '); 9 | const A = parseInt(input[0]); 10 | const B = parseInt(input[1]); 11 | 12 | // process & output 13 | console.log(sum(B) - sum(A - 1)); 14 | 15 | // function 16 | function sum(x) 17 | { 18 | if (x === 0) return 0; 19 | 20 | let ret = 0; 21 | let sumFrom1toN = n => n * (n + 1) / 2; 22 | let squaredSumFrom1toN = n => n * (n + 1) * (2 * n + 1) / 6; 23 | 24 | // x번째 숫자가 몇인지 구함. 25 | let val = 1; 26 | while (sumFrom1toN(val + 1) <= x) 27 | val++; 28 | 29 | // 합을 구함. 30 | ret = squaredSumFrom1toN(val); 31 | ret += (x - sumFrom1toN(val)) * (++val); 32 | 33 | return ret; 34 | } -------------------------------------------------------------------------------- /12968.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1번 밟을 때는 무조건 통과 3 | 4 | 1*1칸은 2번 이상 밟아야 하면 무조건 실패 5 | 6 | 1*2 칸을 생각해보면 7 | 1-2-1-2... 이런식으로 원하는 횟수를 맞추고 다음 칸으로 이동 가능 8 | -> 칸이 짝수개면 무조건 가능 9 | 10 | 그럼 홀수개면? 11 | 1 1 1 1 0 12 | 1 1 1 1 0 13 | 1 1 1 1 0 14 | 1 1 1 1 0 15 | 0 0 0 0 0 16 | 이런식으로 짝수개 먼저 칠하는거 생각해봤는데 안됨 17 | */ 18 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 19 | const [row, col, count] = require('fs') 20 | .readFileSync(INPUT_FILE) 21 | .toString() 22 | .trim() 23 | .split(' ') 24 | .map(Number); 25 | 26 | if (count === 1) console.log(1); 27 | else if ((row * col) % 2 === 0) console.log(1); 28 | else console.log(0); 29 | -------------------------------------------------------------------------------- /13022.js: -------------------------------------------------------------------------------- 1 | /* 2 | 정규식은 힘들어보이니 그냥 세기 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const input = require('fs').readFileSync(INPUT_FILE).toString().trim().split(''); 6 | 7 | let isValid = true; 8 | 9 | while (input.length) { 10 | let wCount = 0; 11 | let oCount = 0; 12 | let lCount = 0; 13 | let fCount = 0; 14 | 15 | while (input.length && input.at(-1) === 'f') { 16 | input.pop(); 17 | fCount += 1; 18 | } 19 | 20 | while (input.length && input.at(-1) === 'l') { 21 | input.pop(); 22 | lCount += 1; 23 | } 24 | 25 | while (input.length && input.at(-1) === 'o') { 26 | input.pop(); 27 | oCount += 1; 28 | } 29 | 30 | while (input.length && input.at(-1) === 'w') { 31 | input.pop(); 32 | wCount += 1; 33 | } 34 | 35 | if (!(wCount === oCount && oCount === lCount && lCount === fCount)) { 36 | isValid = false; 37 | break; 38 | } 39 | } 40 | 41 | console.log(isValid ? 1 : 0); 42 | -------------------------------------------------------------------------------- /1309.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i, 왼쪽) := i번째 줄의 왼쪽에 반드시 사자를 배치할 때 경우의 수 3 | opt(i, 왼쪽) = 4 | i-1번째 줄까지 가능한 모든 경우의 수에서 5 | i-1번째 줄의 왼쪽에 사자가 있는 경우의 수를 빼면 된다. 6 | 7 | prev := opt(i-1, 왼쪽/오른쪽) 을 나타내는 수. 8 | opt(i-1, 왼쪽)=opt(i-1, 오른쪽) 이라 변수 하나로 통일. 9 | cur := 마찬가지로 opt(i, 왼쪽/오른쪽) 을 나타내는 수. 10 | */ 11 | 12 | // input 13 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 14 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 15 | 16 | // process 17 | let prev = 1; 18 | let sum = 3; 19 | 20 | for(let i=1; i b - a); 21 | 22 | for (let i=K-1; i 0) 15 | sol += Math.ceil(room / C); 16 | } 17 | 18 | // output 19 | console.log(sol); -------------------------------------------------------------------------------- /13496.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...inputs] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const sol = []; 10 | let i = 0; 11 | while (i < inputs.length) { 12 | const [shipCount, speed, dueDate] = inputs[i]; 13 | i += 1; 14 | let totalMoney = 0; 15 | 16 | for (let j = 0; j < shipCount; j += 1, i += 1) { 17 | const [distance, money] = inputs[i]; 18 | if (Math.ceil(distance / speed) <= dueDate) { 19 | totalMoney += money; 20 | } 21 | } 22 | 23 | sol.push(totalMoney); 24 | } 25 | 26 | console.log(sol.map((money, index) => `Data Set ${index + 1}:\n${money}`).join('\n\n')); 27 | -------------------------------------------------------------------------------- /1351_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 문제에서 준 점화식 그대로 구현 3 | >> 메모리 초과 나옴 4 | 5 | A의 값들 중 정말 A(N) 계산에 필요한 것들만 계산하되 6 | 메모이제이션 기법도 써야 함 7 | >> 재귀 + Map 8 | */ 9 | 10 | // input 11 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 12 | const [N, P, Q] = require('fs').readFileSync(inputFile).toString().trim().split(' ').map(Number); 13 | 14 | // process & output 15 | const A = new Map(); 16 | A.set(0, 1); 17 | console.log(findValue(N)); 18 | 19 | // functions 20 | function findValue(val) 21 | { 22 | if (A.has(val)) 23 | return A.get(val); 24 | 25 | A.set(val, findValue(Math.floor(val / P)) + findValue(Math.floor(val / Q))); 26 | return A.get(val); 27 | } -------------------------------------------------------------------------------- /13702.js: -------------------------------------------------------------------------------- 1 | /* 2 | 이분탐색 3 | 4 | 움직이는 값: 1인당 막걸리 용량 5 | 비교값: 움직이는 값만큼 분배했을 때 먹을 수 있는 인원수 6 | 기준점: 총 인원수 7 | 8 | 비교값이 기준점보다 작으면 1인당 용량 줄임 9 | 비교값이 기준점보다 크거나 같으면 1인당 용량 늘림 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [, peopleCount, ...kettles] = require('fs').readFileSync(INPUT_FILE).toString().trim() 13 | .split(/\s/) 14 | .map(Number); 15 | 16 | const howManyCanDrink = (cupSize) => kettles.reduce( 17 | (prev, kettle) => prev + Math.floor(kettle / cupSize), 18 | 0, 19 | ); 20 | 21 | let left = 0; 22 | let right = Math.max(...kettles) + 1; 23 | 24 | while (left < right) { 25 | const mid = Math.floor((left + right) / 2); 26 | 27 | if (howManyCanDrink(mid) < peopleCount) right = mid; 28 | else left = mid + 1; 29 | } 30 | 31 | console.log(left - 1); 32 | -------------------------------------------------------------------------------- /1406_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 커서를 기준으로 왼쪽/오른쪽을 나타내는 스택 사용 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [initialString, , ...commands] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n'); 10 | 11 | const left = Array.from(initialString); 12 | const right = []; 13 | 14 | commands.forEach((command) => { 15 | const [type, value] = command.split(' '); 16 | 17 | switch (type) { 18 | case 'L': 19 | if (left.length > 0) right.push(left.pop()); 20 | break; 21 | case 'D': 22 | if (right.length > 0) left.push(right.pop()); 23 | break; 24 | case 'B': 25 | if (left.length > 0) left.pop(); 26 | break; 27 | default: 28 | left.push(value); 29 | } 30 | }); 31 | 32 | console.log(`${left.join('')}${right.reverse().join('')}`); 33 | -------------------------------------------------------------------------------- /1411.js: -------------------------------------------------------------------------------- 1 | /* 2 | 시간 널널 3 | -> 쌍 검사는 부담X 4 | 5 | 순서가 바뀌지 않음 << 이게 핵심 6 | 각 단어의 알파벳을 '숫자'로 치환 7 | 알파벳 등장 순서대로 1, 2, ... 이렇게 바꿈 8 | 이미 등장한 알파벳은 앞에서 만든 숫자로 치환 9 | -> 모든 단어를 수열로 바꿀 수 있음 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [, ...words] = require('fs') 13 | .readFileSync(INPUT_FILE) 14 | .toString() 15 | .trim() 16 | .split('\n') 17 | .map((word) => word.split('')); 18 | 19 | const toSequence = (word) => { 20 | const dict = new Map(); 21 | const sequence = []; 22 | 23 | word.forEach((char) => { 24 | if (!dict.has(char)) dict.set(char, dict.size); 25 | sequence.push(dict.get(char)); 26 | }); 27 | 28 | return sequence.join(' '); 29 | }; 30 | 31 | const sequences = words.map(toSequence); 32 | let count = 0; 33 | 34 | for (let i = 0; i < sequences.length; i += 1) { 35 | for (let j = i + 1; j < sequences.length; j += 1) { 36 | if (sequences[i] === sequences[j]) count += 1; 37 | } 38 | } 39 | 40 | console.log(count); 41 | -------------------------------------------------------------------------------- /1417.js: -------------------------------------------------------------------------------- 1 | /* 2 | 숫자가 작으니 완전탐색 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [, dasom, ...votes] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n') 10 | .map(Number); 11 | 12 | const findThreateningCandidate = () => { 13 | let candidate = -1; 14 | let maxVote = 0; 15 | 16 | votes.forEach((vote, index) => { 17 | if (vote > maxVote) { 18 | maxVote = vote; 19 | candidate = index; 20 | } 21 | }); 22 | 23 | return candidate; 24 | }; 25 | 26 | let dasomVote = dasom; 27 | 28 | for ( 29 | let candidate = findThreateningCandidate(); 30 | dasomVote <= votes[candidate]; 31 | candidate = findThreateningCandidate() 32 | ) { 33 | dasomVote += 1; 34 | votes[candidate] -= 1; 35 | } 36 | 37 | console.log(dasomVote - dasom); 38 | -------------------------------------------------------------------------------- /14219.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3*1짜리가 있으므로 가로나 세로 중 하나는 자유 3 | 나머지는 3의 배수여야함 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [width, height] = require('fs').readFileSync(INPUT_FILE).toString().trim() 7 | .split(' ') 8 | .map(Number); 9 | 10 | console.log((width * height) % 3 === 0 ? 'YES' : 'NO'); 11 | -------------------------------------------------------------------------------- /14232.js: -------------------------------------------------------------------------------- 1 | /* 2 | 모든 보석을 곱했을 때 무게가 나와야 한다? 3 | -> 소인수분해 4 | "그 체"를 쓰기에는 배열이 너무 큼 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const weight = Number(require('fs').readFileSync(INPUT_FILE).toString()); 8 | 9 | const findFirstDivisor = (value) => { 10 | const root = Math.round(Math.sqrt(value)); 11 | for (let i = 2; i <= root; i += 1) { 12 | if (value % i === 0) return i; 13 | } 14 | return value; 15 | }; 16 | 17 | let remainingWeight = weight; 18 | const gems = []; 19 | 20 | while (remainingWeight > 1) { 21 | const gem = findFirstDivisor(remainingWeight); 22 | 23 | while (remainingWeight > 1 && remainingWeight % gem === 0) { 24 | gems.push(gem); 25 | remainingWeight /= gem; 26 | } 27 | } 28 | 29 | console.log(`${gems.length}\n${gems.join(' ')}`); 30 | -------------------------------------------------------------------------------- /1434.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, boxes, books] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | let remainders = 0; 10 | let book = 0; 11 | 12 | for (let box = 0; box < boxes.length; box += 1) { 13 | while (book < books.length && boxes[box] >= books[book]) { 14 | boxes[box] -= books[book]; 15 | book += 1; 16 | } 17 | remainders += boxes[box]; 18 | } 19 | 20 | console.log(remainders); 21 | -------------------------------------------------------------------------------- /14382.js: -------------------------------------------------------------------------------- 1 | /* 2 | 잠들지 못하는 경우가 0 말고 있을까? 3 | 숫자가 충분히 커지면 가장 큰 자릿수에서 1~9를 채울 수 있지 않을까? 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, ...cases] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map(Number); 12 | 13 | const solve = (startValue) => { 14 | if (startValue === 0) return 'INSOMNIA'; 15 | 16 | const appeared = new Set(); 17 | let i; 18 | 19 | for (i = startValue; appeared.size < 10; i += startValue) { 20 | i.toString() 21 | .split('') 22 | .forEach((value) => appeared.add(value)); 23 | } 24 | 25 | return i - startValue; 26 | }; 27 | 28 | const sol = []; 29 | 30 | cases.forEach((value, index) => { 31 | sol.push(`Case #${index + 1}: ${solve(value)}`); 32 | }); 33 | 34 | console.log(sol.join('\n')); 35 | -------------------------------------------------------------------------------- /1440.js: -------------------------------------------------------------------------------- 1 | /* 2 | 어차피 많아야 6종류 -> 그냥 완탐ㄱ 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const time = require('fs').readFileSync(INPUT_FILE).toString().trim().split(':').map(Number); 6 | 7 | const isHour = (value) => value >= 1 && value <= 12; 8 | const isMinuteOrSecond = (value) => value <= 59; 9 | const candidates = ['hms', 'hsm', 'mhs', 'msh', 'shm', 'smh']; 10 | const isValid = (value, target) => { 11 | if (target === 'h') return isHour(value); 12 | return isMinuteOrSecond(value); 13 | }; 14 | 15 | const sol = candidates.filter( 16 | (candidate) => 17 | isValid(time[0], candidate[0]) && 18 | isValid(time[1], candidate[1]) && 19 | isValid(time[2], candidate[2]), 20 | ).length; 21 | 22 | console.log(sol); 23 | -------------------------------------------------------------------------------- /14430.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i, j)를 (1, 1)부터 (i, j)까지 탐색가능 최대자원이라 하면 3 | opt(i, j) = 4 | opt(i-1, j) 5 | opt(i, j-1) 6 | 둘 중 큰 값에다가 7 | 만약 (i, j)에 자원이 있으면 +1 8 | */ 9 | 10 | // input 11 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 12 | const input = require('fs').readFileSync(inputFile).toString().trim().split('\n'); 13 | 14 | const [row, col] = input[0].split(' ').map(x => parseInt(x)); 15 | 16 | let area = []; 17 | for(let i=1; i parseInt(x))); 19 | 20 | // process 21 | for(let r=0; r 0? area[r - 1][c] : 0; 26 | let val2 = c > 0? area[r][c - 1] : 0; 27 | area[r][c] += Math.max(val1, val2); 28 | } 29 | } 30 | 31 | // output 32 | console.log(area[row - 1][col - 1]); -------------------------------------------------------------------------------- /14494.js: -------------------------------------------------------------------------------- 1 | /* 2 | D[i][j] = D[i-1][j] + D[i][j-1] + D[i-1][j-1] 3 | */ 4 | 5 | // input 6 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 7 | const [row, col] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(x => parseInt(x)); 8 | 9 | // process 10 | let D = Array.from(Array(row + 1), () => new Array(col + 1)); 11 | D[0][0] = 1; // 루프에서 D[1][1]=1로 설정해주기 위함 12 | 13 | for(let r=1; r<=row; r++) 14 | { 15 | for(let c=1; c<=col; c++) 16 | { 17 | let val1 = D[r - 1][c] === undefined? 0 : D[r - 1][c]; 18 | let val2 = D[r][c - 1] === undefined? 0 : D[r][c - 1]; 19 | let val3 = D[r - 1][c - 1] === undefined? 0 : D[r - 1][c - 1]; 20 | D[r][c] = (val1 + val2 + val3) % 1000000007; 21 | } 22 | } 23 | 24 | // output 25 | console.log(D[row][col]); -------------------------------------------------------------------------------- /14495.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const n = Number(require('fs').readFileSync(INPUT_FILE).toString()); 3 | 4 | const fiboLike = [0, 1, 1, 1, 2, 3, 4, 6, 9, 13, 19].map(BigInt); 5 | 6 | for (let i = fiboLike.length; i <= n; i += 1) { 7 | fiboLike.push(fiboLike[i - 1] + fiboLike[i - 3]); 8 | } 9 | 10 | console.log(fiboLike[n].toString()); 11 | -------------------------------------------------------------------------------- /14501.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := i일에 퇴사할 때 받는 금액 3 | opt(i) = 4 | opt(i-1) 5 | opt(k) + P(k) 6 | k는 kS면 D/2만큼은 대각선으로 움직이고 나머지는 가로세로로 이동 12 | */ 13 | // input 14 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 15 | const [X, Y, W, S] = require('fs').readFileSync(inputFile).toString().trim().split(' ').map(Number); 16 | 17 | // process 18 | const A = Math.min(X, Y); 19 | let sol = Math.min(2 * W, S) * A; 20 | const D = (Math.max(X, Y) - A); 21 | sol += W <= S? D * W : parseInt(D / 2) * 2 * S + (D % 2) * W; 22 | 23 | // output 24 | console.log(sol); -------------------------------------------------------------------------------- /1463.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := i를 1로 만드는 데 필요한 최소 연산 횟수 3 | opt(i) = 4 | opt(i/3) 단, i%3=0 5 | opt(i/2) 단, i%2=0 6 | opt(i-1) 7 | 셋 중 최솟값에 1을 더한 값 8 | */ 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const target = Number(require('fs').readFileSync(INPUT_FILE).toString()); 11 | 12 | const counts = [Infinity, 0]; 13 | 14 | for (let i = 2; i <= target; i += 1) { 15 | counts.push(1 + Math.min( 16 | counts[i / 3] ?? Infinity, 17 | counts[i / 2] ?? Infinity, 18 | counts[i - 1], 19 | )); 20 | } 21 | 22 | console.log(counts[target]); 23 | -------------------------------------------------------------------------------- /14650.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i, 0) := i자리 수 중 3으로 나눈 나머지가 0인 수의 개수 3 | opt(i, 1) := i자리 수 중 3으로 나눈 나머지가 1인 수의 개수 4 | opt(i, 2) := i자리 수 중 3으로 나눈 나머지가 2인 수의 개수 5 | 6 | opt(i, 0) = opt(i-1, 0) + opt(i-1, 1) + opt(i-1, 2) 7 | 나머지가 0인 수 뒤에 0을 붙이거나 8 | 1인 수 뒤에 2를 붙이거나 9 | 2인 수 뒤에 1을 붙이면 되삼 10 | 11 | 같은 방법으로 opt(i, 1), opt(i, 2)도 구할 수 있삼. 12 | */ 13 | 14 | // input 15 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 16 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 17 | 18 | // process 19 | opt = [[0, 0], [0, 1], [0, 1]]; 20 | 21 | for(let i=2; i<=N; i++) 22 | { 23 | let val = opt[0][i - 1] + opt[1][i - 1] + opt[2][i - 1]; 24 | opt[0].push(val); 25 | opt[1].push(val); 26 | opt[2].push(val); 27 | } 28 | 29 | // output 30 | console.log(opt[0][N]); -------------------------------------------------------------------------------- /14651.js: -------------------------------------------------------------------------------- 1 | /* 2 | i자리 3의 배수의 개수 = 3 | i-1자리이고 3으로 나눈 나머지가 1인 수에 2를 붙임 4 | i-1자리이고 3으로 나눈 나머지가 2인 수에 1를 붙임 5 | i-1자리이고 3의 배수인 수에 0을 붙임 6 | 7 | 같은 방식으로 3으로 나눴을 때 8 | 나머지가 1, 2인 수의 개수도 구할 수 있음. 9 | 10 | opt(i, {0,1,2}) := i자리이고 3으로 나눈 나머지가 0,1,2 11 | 근데 결국 opt(i,0), opt(i,1), opt(i,2) 모두 점화식이 12 | opt(i-1,0) + opt(i-1,1) + opt(i-1,2) 13 | 이거로 통일됨. 14 | 15 | 즉 opt(i) = 3 * opt(i-1) 16 | 17 | 계산엔 opt(i), opt(i-1)만 있으면 됨 18 | >> 하나의 변수로 처리 가능 19 | */ 20 | 21 | // input 22 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 23 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 24 | 25 | // process 26 | let opt = N == 1? 0 : 2; // opt(1)=0, opt(2)=2 27 | 28 | for (let i=3; i<=N; i++) 29 | opt = (3 * opt) % 1000000009; 30 | 31 | // output 32 | console.log(opt); -------------------------------------------------------------------------------- /14720.js: -------------------------------------------------------------------------------- 1 | /* 2 | 무조건 0부터 시작해서 012012012... 순서임 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [, ...stores] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split(/\s/) 10 | .map(Number); 11 | 12 | let next = 0; 13 | let count = 0; 14 | 15 | for (let i = 0; i < stores.length; i += 1) { 16 | if (stores[i] === next) { 17 | count += 1; 18 | next += 1; 19 | next %= 3; 20 | } 21 | } 22 | 23 | console.log(count); 24 | -------------------------------------------------------------------------------- /1475.js: -------------------------------------------------------------------------------- 1 | /* 2 | 6과 9를 한 세트로 취급: 9를 6으로 바꿈. 3 | 즉 한 세트당 0,1,2,3,4,5,7,8은 1개, 6은 2개 주어지는 셈. 4 | */ 5 | 6 | // input 7 | const inputFile = __dirname + '/input'; // '/dev/stdin'; 8 | const input = require('fs').readFileSync(inputFile).toString().trim().split(''); 9 | 10 | // process 11 | let digit = new Array(9); 12 | digit.fill(0); 13 | 14 | // 방번호의 각 자릿수를 확인, 몇 개 필요한지 계산 15 | for (let val of input) 16 | { 17 | val = parseInt(val); 18 | 19 | if (val == 9) 20 | val = 6; 21 | 22 | digit[val]++; 23 | } 24 | 25 | // 각 숫자별로 몇 세트씩 필요한지 계산 26 | let sol = 0; 27 | 28 | for (let i in digit) 29 | { 30 | let need; 31 | 32 | if (i != 6) 33 | need = digit[i]; 34 | 35 | else 36 | need = Math.ceil(digit[i] / 2); 37 | 38 | sol = Math.max(sol, need); 39 | } 40 | 41 | // output 42 | console.log(sol); -------------------------------------------------------------------------------- /14852.js: -------------------------------------------------------------------------------- 1 | /* 2 | 2*1 크기의 벽을 채우는 방법 3 | 2가지 4 | 5 | 2*2 크기의 벽을 반드시 1*2 벽을 하나이상 써서 채우는 방법 6 | 3가지 7 | 8 | 2*k, k는 3 이상인 홀수에 대해 9 | ㅡ- 10 | -ㅡ 11 | 12 | ㅡㅡ- 13 | -ㅡㅡ 14 | 15 | ㅡㅡㅡ- 16 | -ㅡㅡㅡ 17 | 이런식으로 늘리기 가능 18 | 19 | 2*k, k는 4 이상인 짝수에 대해 20 | ㅡㅡ 21 | -ㅡ- 22 | 23 | ㅡㅡㅡ 24 | -ㅡㅡ- 25 | 26 | ㅡㅡㅡㅡㅡ 27 | -ㅡㅡㅡㅡ- 28 | 이런식으로 늘리기가 가능 29 | 30 | opt(i) = 31 | opt(i-1) * 2 32 | opt(i-2) * 3 33 | opt(i-k) * 2, k>=3인 자연수 34 | 이걸 다 더한 것. 35 | 36 | opt(i-k) * 2 이걸 매번 순회하긴 비싸니까 37 | 저것들의 합을 따로 저장하는 변수 사용. 38 | */ 39 | 40 | // input 41 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 42 | const N = Number(require('fs').readFileSync(inputFile).toString().trim()); 43 | const mod = 1000000007; 44 | 45 | // process 46 | const opt = [1, 2, 7]; 47 | let sum = 0; 48 | 49 | for (let i=3; i<=N; i++) 50 | { 51 | sum = (sum + opt[i - 3]) % mod; 52 | opt.push((opt[i - 1] * 2 + opt[i - 2] * 3 + sum * 2) % mod); 53 | } 54 | 55 | // output 56 | console.log(opt[N]); -------------------------------------------------------------------------------- /14916.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 거스름돈 i원을 주는 데 필요한 최소 동전 개수 3 | 4 | opt(i) = min(opt(i-2), opt(i-5)) + 1 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const money = Number(require('fs').readFileSync(INPUT_FILE).toString()); 8 | 9 | const coinCount = [0]; 10 | 11 | for (let i = 1; i <= money; i += 1) { 12 | coinCount.push(1 + Math.min( 13 | i < 2 ? Infinity : coinCount[i - 2], 14 | i < 5 ? Infinity : coinCount[i - 5], 15 | )); 16 | } 17 | 18 | console.log(coinCount[money] === Infinity ? -1 : coinCount[money]); 19 | -------------------------------------------------------------------------------- /1495.js: -------------------------------------------------------------------------------- 1 | /* 2 | 어차피 볼륨은 0~1000 중 하나. 3 | >> 각 곡별로 연주 가능한 볼륨 집합을 만듦. 4 | */ 5 | 6 | // input 7 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 8 | const [N, S, M, ... V] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(x => parseInt(x)); 9 | 10 | // process 11 | let prev = new Set([S]); 12 | 13 | for (let i=0; i= 0) 20 | cur.add(vol - V[i]); 21 | if (vol + V[i] <= M) 22 | cur.add(vol + V[i]); 23 | } 24 | 25 | prev = cur; 26 | } 27 | 28 | // output 29 | let sol = -1; 30 | for (let vol of prev) 31 | if (vol > sol) sol = vol; 32 | console.log(sol); -------------------------------------------------------------------------------- /15552.js: -------------------------------------------------------------------------------- 1 | const inputFile = __dirname + '/input'; // '/dev/stdin'; 2 | const input = require("fs").readFileSync(inputFile).toString().trim().split(/\s/); 3 | 4 | let T = parseInt(input[0]); 5 | let idx = 1; 6 | let sol = []; 7 | 8 | while (T > 0) 9 | { 10 | sol.push(parseInt(input[idx++]) + parseInt(input[idx++])); 11 | T--; 12 | } 13 | 14 | console.log(sol.join('\n')); -------------------------------------------------------------------------------- /15565.js: -------------------------------------------------------------------------------- 1 | /* 2 | dp는 아닌거같은데 dp 맞나 3 | 4 | ryan(i) := i번째 라이언 인형의 위치 5 | opt(i) := 6 | i번쨰 라이언 인형을 마지막으로 했을 때 7 | 라이언 인형이 k개 이상 있는 가장 작은 연속된 인형들의 집합의 크기 8 | opt(i) = ryan(i) - ryan(i-k+1) + 1 9 | */ 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [, neededRyan, ...dolls] = require('fs') 12 | .readFileSync(INPUT_FILE) 13 | .toString() 14 | .trim() 15 | .split(/\s/) 16 | .map(Number); 17 | 18 | const ryan = []; 19 | dolls.forEach((value, index) => { 20 | if (value === 1) ryan.push(index); 21 | }); 22 | 23 | let sol = Infinity; 24 | for (let i = neededRyan - 1; i < ryan.length; i += 1) { 25 | const size = ryan[i] - ryan[i - neededRyan + 1] + 1; 26 | if (size < sol) sol = size; 27 | } 28 | 29 | console.log(sol !== Infinity ? sol : -1); 30 | -------------------------------------------------------------------------------- /15610.js: -------------------------------------------------------------------------------- 1 | /* 2 | 자스 숫자는 15자리부터 위험 3 | 입력이 18자리까지 오는데 -> 10000으로 나눠서 소수점 추가해버리고 4 | 스퀘어루트 먹인다음에 100 곱하면될듯? 5 | 6 | 답 자체는 루트하고 4곱하면됨 7 | */ 8 | const INPUIT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const input = require('fs').readFileSync(INPUIT_FILE).toString().trim(); 10 | 11 | const isNotSafeNumber = input.length >= 15; 12 | const value = isNotSafeNumber 13 | ? Number(`${input.slice(0, input.length - 4)}.${input.slice(input.length - 4)}`) 14 | : Number(input); 15 | 16 | console.log(Math.sqrt(value) * 4 * (isNotSafeNumber ? 100 : 1)); 17 | -------------------------------------------------------------------------------- /15719.js: -------------------------------------------------------------------------------- 1 | // 메모리 초과 2 | 3 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 4 | const [_, ...sequence] = require('fs').readFileSync(INPUT_FILE).toString().trim() 5 | .split(/\s/) 6 | .map(Number); 7 | 8 | const appearedNumbers = new Set(); 9 | 10 | const sol = sequence.find((number) => { 11 | if (appearedNumbers.has(number)) return true; 12 | 13 | appearedNumbers.add(number); 14 | return false; 15 | }); 16 | 17 | console.log(sol); 18 | -------------------------------------------------------------------------------- /15719_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 배열을 사용할 경우 메모리 초과 3 | 4 | char 하나씩 읽어서 숫자를 찾아야 함 5 | 6 | 처음 수열에 들어 있던 수의 합: 1부터 N-1까지 정수의 합 7 | 삽입 후 수열에 들어 있던 수의 합: 윗줄서 구한 합 + 삽입한 값 8 | */ 9 | 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [length, sequence] = require('fs').readFileSync(INPUT_FILE).toString().trim() 12 | .split('\n'); 13 | 14 | let sum = ((Number(length) - 1) * Number(length)) / 2; 15 | let currentNumber = []; 16 | 17 | for (let i = 0; i < sequence.length; i += 1) { 18 | if (sequence[i] === ' ') { 19 | sum -= Number(currentNumber.join('')); 20 | currentNumber = []; 21 | } else { 22 | currentNumber.push(sequence[i]); 23 | } 24 | } 25 | sum -= Number(currentNumber.join('')); 26 | 27 | console.log(-sum); 28 | -------------------------------------------------------------------------------- /15719_v3.js: -------------------------------------------------------------------------------- 1 | /* 2 | 배열을 사용할 경우 메모리 초과 3 | 4 | char 하나씩 읽어서 숫자를 찾아야 함 5 | 6 | 처음 수열에 들어 있던 수의 합: 1부터 N-1까지 정수의 합 7 | 삽입 후 수열에 들어 있던 수의 합: 윗줄서 구한 합 + 삽입한 값 8 | 9 | 숫자를 거꾸로 읽으면 현재 숫자를 배열에 저장할 필요조차 없다? 10 | 띄어쓰기 후 처음 만난애 = 일의 자리 11 | 그 다음 = 십의 자리 12 | 그 다음 = 백의 자리 13 | 띄어쓰기 = 자리 초기화 14 | */ 15 | 16 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 17 | const [length, sequence] = require('fs').readFileSync(INPUT_FILE).toString().trim() 18 | .split('\n'); 19 | 20 | let sum = ((Number(length) - 1) * Number(length)) / 2; 21 | let base = 1; 22 | 23 | for (let i = sequence.length - 1; i >= 0; i -= 1) { 24 | if (sequence[i] === ' ') { 25 | base = 1; 26 | } else { 27 | sum -= Number(sequence[i]) * base; 28 | base *= 10; 29 | } 30 | } 31 | 32 | console.log(-sum); 33 | -------------------------------------------------------------------------------- /15724.js: -------------------------------------------------------------------------------- 1 | /* 2 | 누적합 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [[row, col], ...inputs] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n') 10 | .map((line) => line.split(' ').map(Number)); 11 | 12 | const land = inputs.slice(0, row); 13 | const questions = inputs.slice(1 + row); 14 | 15 | for (let r = 0; r < row; r += 1) { 16 | for (let c = 0; c < col; c += 1) { 17 | land[r][c] += (land[r - 1]?.[c] ?? 0) + (land[r][c - 1] ?? 0) - (land[r - 1]?.[c - 1] ?? 0); 18 | } 19 | } 20 | 21 | const sol = questions.map((coordinates) => { 22 | const [r1, c1, r2, c2] = coordinates.map((val) => val - 1); 23 | return ( 24 | land[r2][c2] - 25 | (land[r1 - 1]?.[c2] ?? 0) - 26 | (land[r2][c1 - 1] ?? 0) + 27 | (land[r1 - 1]?.[c1 - 1] ?? 0) 28 | ); 29 | }); 30 | 31 | console.log(sol.join('\n')); 32 | -------------------------------------------------------------------------------- /15964.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [A, B] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(' ') 4 | .map(Number); 5 | 6 | console.log((A + B) * (A - B)); 7 | -------------------------------------------------------------------------------- /15970.js: -------------------------------------------------------------------------------- 1 | /* 2 | 그냥 분류해서 정렬하는 문제. 3 | */ 4 | const [, ...points] = require('fs') 5 | .readFileSync(0, 'utf-8') 6 | .toString() 7 | .trim() 8 | .split('\n') 9 | .map((line) => line.split(' ').map(Number)); 10 | 11 | points.sort((a, b) => a[0] - b[0]); 12 | const colorPoints = Array.from({ length: points.length + 1 }, () => []); 13 | for (let i = 0; i < points.length; i += 1) { 14 | colorPoints[points[i][1]].push(points[i][0]); 15 | } 16 | 17 | const sol = colorPoints 18 | .map((pointList) => { 19 | return pointList.reduce((prev, cur, idx) => { 20 | return ( 21 | prev + 22 | Math.min(cur - (pointList[idx - 1] ?? -Infinity), (pointList[idx + 1] ?? Infinity) - cur) 23 | ); 24 | }, 0); 25 | }) 26 | .reduce((prev, cur) => prev + cur); 27 | 28 | console.log(sol); 29 | -------------------------------------------------------------------------------- /1598.js: -------------------------------------------------------------------------------- 1 | /* 2 | 편의를 위해 모든 수를 1씩 빼서 생각 3 | 4 | 어떤 숫자 x에 대해 5 | 행: x % 4 6 | 열: x // 4 7 | */ 8 | const [a, b] = require('fs').readFileSync('input').toString().trim() 9 | .split(' ') 10 | .map((value) => Number(value) - 1); 11 | 12 | const verticalDistance = Math.abs((a % 4) - (b % 4)); 13 | const horizontalDistance = Math.abs(Math.floor(a / 4) - Math.floor(b / 4)); 14 | 15 | console.glo(verticalDistance + horizontalDistance); 16 | -------------------------------------------------------------------------------- /15989.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i, k) := i를 만드는데 마지막에 더한 수가 k인 경우의 수 3 | opt(i, 1) = opt(i-1, {1,2,3}) 4 | opt(i, 2) = opt(i-2, {2,3}) 5 | opt(i, 3) = opt(i-3, {3}) 6 | 7 | 1 8 | 11 2 9 | 111 21 3 10 | */ 11 | 12 | // input 13 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 14 | const [T, ... N] = require('fs').readFileSync(inputFile).toString().trim().split('\n').map(x => parseInt(x)); 15 | 16 | // process 17 | let opt_1 = [0, 1, 1, 2]; 18 | let opt_2 = [0, 0, 1, 0]; 19 | let opt_3 = [0, 0, 0, 1]; 20 | let i = 4; 21 | let sol = []; 22 | 23 | for (let n of N) 24 | { 25 | while (i <= n) 26 | { 27 | opt_1.push(opt_1[i - 1] + opt_2[i - 1] + opt_3[i - 1]); 28 | opt_2.push(opt_2[i - 2] + opt_3[i - 2]); 29 | opt_3.push(opt_3[i - 3]); 30 | i++; 31 | } 32 | 33 | sol.push(opt_1[n] + opt_2[n] + opt_3[n]); 34 | } 35 | 36 | // output 37 | console.log(sol.join('\n')); -------------------------------------------------------------------------------- /15993.js: -------------------------------------------------------------------------------- 1 | /* 2 | dp 3 | opt(i, 홀/짝):= i를 만드는 경우의 수가 홀수/짝수인 경우 4 | opt(i, 홀) = opt(i-1, 짝) + opt(i-2, 짝) + opt(i-3, 짝) 5 | opt(i, 짝) = opt(i-1, 홀) + opt(i-2, 홀) + opt(i-3, 홀) 6 | 7 | 1 8 | 11 2 9 | 12 21 111 3 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [, ...numbers] = require('fs') 13 | .readFileSync(INPUT_FILE) 14 | .toString() 15 | .trim() 16 | .split('\n') 17 | .map(Number); 18 | 19 | const DIVISOR = 1_000_000_009; 20 | const optOdd = [0, 1, 1, 2]; 21 | const optEven = [0, 0, 1, 2]; 22 | const sol = numbers 23 | .map((num) => { 24 | while (optOdd.length <= num) { 25 | const nextOdd = (optEven.at(-1) + optEven.at(-2) + optEven.at(-3)) % DIVISOR; 26 | const nextEven = (optOdd.at(-1) + optOdd.at(-2) + optOdd.at(-3)) % DIVISOR; 27 | optOdd.push(nextOdd); 28 | optEven.push(nextEven); 29 | } 30 | return `${optOdd[num]} ${optEven[num]}`; 31 | }) 32 | .join('\n'); 33 | 34 | console.log(sol); 35 | -------------------------------------------------------------------------------- /16099.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [N, ...testCases] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map((line) => line.split(' ').map(BigInt)); 5 | 6 | const results = []; 7 | const findWinner = (a, b, x, y) => { 8 | const telecomParisTech = a * b; 9 | const eurecom = x * y; 10 | if (telecomParisTech < eurecom) return 'Eurecom'; 11 | if (telecomParisTech > eurecom) return 'TelecomParisTech'; 12 | return 'Tie'; 13 | }; 14 | 15 | testCases.forEach((values) => { 16 | results.push(findWinner(...values)); 17 | }); 18 | 19 | console.log(results.join('\n')); 20 | -------------------------------------------------------------------------------- /16114.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1. 무조건 컴파일 에러 3 | 길이가 1보다 큰 홀수 4 | 2. 무조건 0 5 | 시작값 음수, 길이 1 아님 6 | 시작값 양수, 길이 1 7 | 시작값 0 8 | 3. 무조건 무한대 9 | 시작값 양수, 길이 0 10 | 시작값 음수, 길이 1 11 | 4. 계산 12 | */ 13 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 14 | const [initialValue, arrowLength] = require('fs') 15 | .readFileSync(INPUT_FILE) 16 | .toString() 17 | .trim() 18 | .split(' ') 19 | .map(Number); 20 | 21 | if (arrowLength > 1 && arrowLength % 2 === 1) { 22 | console.log('ERROR'); 23 | } else if ( 24 | initialValue === 0 || 25 | (initialValue <= 0 && arrowLength !== 1) || 26 | (initialValue >= 0 && arrowLength === 1) 27 | ) { 28 | console.log(0); 29 | } else if (arrowLength === 0 || (initialValue < 0 && arrowLength === 1)) { 30 | console.log('INFINITE'); 31 | } else { 32 | console.log(Math.ceil(initialValue / (arrowLength / 2)) - 1); 33 | } 34 | -------------------------------------------------------------------------------- /16194.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 카드 i개를 갖기 위해 내야 하는 최소 금액 3 | opt(i) = 4 | opt(i-1) + P(1) 5 | opt(i-2) + P(2) 6 | opt(i-3) + P(3) 7 | ... 8 | opt(i-N) + P(N) 9 | 이 중 최솟값. 10 | */ 11 | 12 | // input 13 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 14 | const [N, ... P] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(x => parseInt(x)); 15 | 16 | // process 17 | let opt = [0]; 18 | 19 | for (let i=1; i<=N; i++) 20 | { 21 | let val = Infinity; 22 | 23 | for (let k=1; k<=i; k++) 24 | { 25 | if (val > opt[i - k] + P[k - 1]) 26 | val = opt[i - k] + P[k - 1]; 27 | } 28 | 29 | opt.push(val); 30 | } 31 | 32 | // output 33 | console.log(opt[N]); -------------------------------------------------------------------------------- /16198.js: -------------------------------------------------------------------------------- 1 | /* 2 | 구슬 10개밖에 없어서 완탐가능 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [, ...balls] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split(/\s/) 10 | .map(Number); 11 | 12 | const gatherEnergy = (balls, energy) => { 13 | if (balls.length === 2) { 14 | return energy; 15 | } 16 | 17 | let max = 0; 18 | for (let i = 1; i < balls.length - 1; i += 1) { 19 | const result = gatherEnergy( 20 | [...balls.slice(0, i), ...balls.slice(i + 1)], 21 | energy + balls[i - 1] * balls[i + 1], 22 | ); 23 | max = Math.max(max, result); 24 | } 25 | 26 | return max; 27 | }; 28 | 29 | console.log(gatherEnergy(balls, 0)); 30 | -------------------------------------------------------------------------------- /16199.js: -------------------------------------------------------------------------------- 1 | const INPUIT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [birthday, today] = require('fs') 3 | .readFileSync(INPUIT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const isBefore = (one, another) => { 10 | const [, month1, date1] = one; 11 | const [, month2, date2] = another; 12 | 13 | return month1 < month2 || (month1 === month2 && date1 < date2); 14 | }; 15 | 16 | const yearDiff = today[0] - birthday[0]; 17 | const age = yearDiff + (isBefore(today, birthday) ? -1 : 0); 18 | const countingAge = yearDiff + 1; 19 | const yearAge = yearDiff; 20 | 21 | console.log([age, countingAge, yearAge].join('\n')); 22 | -------------------------------------------------------------------------------- /16439.js: -------------------------------------------------------------------------------- 1 | /* 2 | 완탐 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [[, chickenCount], ...likes] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n') 10 | .map((line) => line.split(' ').map(Number)); 11 | 12 | function* chickenGenerator() { 13 | for (let i = 0; i < chickenCount; i += 1) { 14 | for (let j = i + 1; j < chickenCount; j += 1) { 15 | for (let k = j + 1; k < chickenCount; k += 1) { 16 | yield [i, j, k]; 17 | } 18 | } 19 | } 20 | } 21 | 22 | const sol = Math.max( 23 | ...Array.from(chickenGenerator()).map((chickens) => { 24 | return likes 25 | .map((member) => Math.max(...chickens.map((chicken) => member[chicken]))) 26 | .reduce((sum, cur) => sum + cur, 0); 27 | }), 28 | ); 29 | 30 | console.log(sol); 31 | -------------------------------------------------------------------------------- /1644_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1. N 이하의 소수를 센다. 3 | 2. 투 포인터로 합이 N 초과면 왼쪽 경계를 움직이고 아니면 오른쪽 경계를 움직인다. 4 | 5 | 확인해보니 소수판별이 오래걸렸음 6 | 에라토스테네스의 체 사용 7 | */ 8 | 9 | // input 10 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 11 | const N = Number(require('fs').readFileSync(inputFile).toString()); 12 | 13 | // process 14 | // N 이하의 소수 세기 15 | const primes = []; 16 | const isPrime = new Array(N + 1).fill(true); 17 | 18 | for (let i=2; i<=N; i++) 19 | { 20 | if (isPrime[i]) 21 | { 22 | primes.push(i); 23 | for (let j=2; i*j<=N; j++) 24 | isPrime[i * j] = false; 25 | } 26 | } 27 | 28 | // 정답 계산 29 | let sol = N == 2? 1 : 0; 30 | let left = 0; 31 | let right = 0; 32 | let sum = 2; 33 | 34 | while (right < primes.length) 35 | { 36 | if (sum > N) 37 | sum -= primes[left++]; 38 | else 39 | sum += primes[++right]; 40 | 41 | if (sum === N) 42 | sol++; 43 | } 44 | 45 | // output 46 | console.log(sol); -------------------------------------------------------------------------------- /16564.js: -------------------------------------------------------------------------------- 1 | /* 2 | 이분 탐색 3 | 4 | 움직이는 값: 팀 목표레벨 T 5 | 기준점: 올릴 수 있는 최대 총합 레벨 K 6 | 비교하는 값: 팀 목표레벨 T를 위해서 올려야 하는 레벨의 총합 7 | 8 | 비교하는 값이 기준점보다 크면 목표레벨을 줄임 9 | 비교하는 값이 기준점보다 작거나 같으면 목표레벨을 늘림 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [, levelUpLimit, ...levels] = require('fs').readFileSync(INPUT_FILE).toString().trim() 13 | .split(/\s/) 14 | .map(Number); 15 | 16 | const getLevelsNeeded = (teamLevel) => levels.reduce( 17 | (prev, level) => prev + Math.max(teamLevel - level, 0), 18 | 0, 19 | ); 20 | 21 | let left = Math.min(...levels); 22 | let right = Math.max(...levels) + levelUpLimit + 1; 23 | 24 | while (left < right) { 25 | const mid = Math.floor((left + right) / 2); 26 | 27 | if (getLevelsNeeded(mid) > levelUpLimit) right = mid; 28 | else left = mid + 1; 29 | } 30 | 31 | console.log(left - 1); 32 | -------------------------------------------------------------------------------- /16568.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 앞에 i명이 있을 때 걸리는 최소 시간 3 | opt(i) = 4 | opt(i-1) 5 | opt(i-1-a) 6 | opt(i-1-b) 7 | 셋 중 최솟값에 1초를 더한 값 8 | */ 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [total, teleportA, teleportB] = require('fs').readFileSync(INPUT_FILE).toString().trim() 11 | .split(' ') 12 | .map(Number); 13 | 14 | const time = [0, 1]; 15 | 16 | for (let i = 2; i <= total; i += 1) { 17 | time.push(1 + Math.min( 18 | time[i - 1], 19 | time[i - 1 - teleportA] ?? Infinity, 20 | time[i - 1 - teleportB] ?? Infinity, 21 | )); 22 | } 23 | 24 | console.log(time[total]); 25 | -------------------------------------------------------------------------------- /1678.js: -------------------------------------------------------------------------------- 1 | /* 2 | 기차들 속도가 다 같다고 가정하면 3 | 출발순서대로 역에 도착하니까 자기가 탄거 바로 다음 출발시간인 기차로 갈아탐 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [info, ...trainInfos] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 7 | 8 | const [, startTime, destination] = info.split(' ').map(Number); 9 | const trains = []; 10 | 11 | trainInfos.forEach((line) => { 12 | const [name, ...times] = line.split(' '); 13 | times.pop(); 14 | times.map(Number).forEach((time) => { 15 | trains.push([time, name]); 16 | }); 17 | }); 18 | 19 | trains.sort((one, another) => one[0] - another[0]); 20 | 21 | const startIndex = Math.max( 22 | trains.findIndex(([time]) => time >= startTime), 23 | 0, 24 | ); 25 | const remainder = destination % trains.length; 26 | 27 | const [, sol] = trains[(startIndex + remainder + trains.length - 1) % trains.length]; 28 | 29 | console.log(sol); 30 | -------------------------------------------------------------------------------- /17212.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) = i원을 지불하는 데 필요한 최소 동전 개수 3 | opt(i) = 4 | opt(i-1) 5 | opt(i-2) 6 | opt(i-5) 7 | opt(i-7) 8 | 넷 중 최솟값 + 1 9 | */ 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const price = Number(require('fs').readFileSync(INPUT_FILE).toString()); 12 | 13 | const minCoinCount = [0, 1, 1]; 14 | 15 | for (let money = 3; money <= price; money += 1) { 16 | minCoinCount.push(1 + Math.min( 17 | money >= 1 ? minCoinCount[money - 1] : Infinity, 18 | money >= 2 ? minCoinCount[money - 2] : Infinity, 19 | money >= 5 ? minCoinCount[money - 5] : Infinity, 20 | money >= 7 ? minCoinCount[money - 7] : Infinity, 21 | )); 22 | } 23 | 24 | console.log(minCoinCount[price]); 25 | -------------------------------------------------------------------------------- /17393.js: -------------------------------------------------------------------------------- 1 | /* 2 | 이분탐색 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [[tileCount], inks, viscosities] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n') 10 | .map((line) => line.split(' ').map(Number)); 11 | 12 | const sol = inks.map((ink, idx) => { 13 | let left = idx + 1; 14 | let right = tileCount; 15 | 16 | while (left < right) { 17 | const mid = Math.floor((left + right) / 2); 18 | 19 | if (viscosities[mid] <= ink) { 20 | left = mid + 1; 21 | } else { 22 | right = mid; 23 | } 24 | } 25 | 26 | const rightEnd = left - 1; 27 | 28 | return rightEnd - idx; 29 | }); 30 | 31 | console.log(sol.join(' ')); 32 | -------------------------------------------------------------------------------- /1748.js: -------------------------------------------------------------------------------- 1 | // input 2 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 3 | const N = Number(require('fs').readFileSync(INPUT_FILE).toString()); 4 | 5 | // process 6 | let sol = 0; 7 | for (let exponent = 0; 10 ** (exponent) <= N; exponent += 1) { 8 | if (10 ** (exponent + 1) <= N) { // 10*exponent자리 숫자가 전부 차 있음 9 | sol += (10 ** (exponent + 1) - 10 ** exponent) * (exponent + 1) + 1; 10 | } else { // 10*exponent자리 숫자 중간에 N이 있음 11 | sol += (N - 10 ** exponent) * (exponent + 1) + 1; 12 | } 13 | } 14 | 15 | // output 16 | console.log(sol); 17 | -------------------------------------------------------------------------------- /1758.js: -------------------------------------------------------------------------------- 1 | /* 2 | 한칸 뒤로 밀림 = 팁 1만큼 덜받음 3 | 결국 앞쪽에서 팁을 1원이라도 받으면 뒤쪽으로 미뤄도 손해는 안 봄 4 | 따라서 팁을 많이주려는 사람을 뒤로 미루고, 팁을 적게주는 사람을 앞으로 배치해서 5 | 1원이라도 팁을 더 받아야함 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const [, ...tips] = require('fs') 9 | .readFileSync(INPUT_FILE) 10 | .toString() 11 | .trim() 12 | .split('\n') 13 | .map(Number); 14 | 15 | tips.sort((one, another) => another - one); 16 | 17 | const totalTip = tips.reduce( 18 | (total, tip, waitingTime) => total + Math.max(tip - waitingTime, 0), 19 | 0, 20 | ); 21 | 22 | console.log(totalTip); 23 | -------------------------------------------------------------------------------- /17626.js: -------------------------------------------------------------------------------- 1 | // 시간 초과 2 | 3 | /* 4 | 50000 이하의 제곱수들을 구한다 -> 일단 300개 아래임 5 | 6 | opt(i) := 합이 i가 되는 제곱수들의 최소 개수 7 | opt(i) = opt(i-k) + 1 (단, k <= i인 제곱수) 8 | */ 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const target = Number(require('fs').readFileSync(INPUT_FILE).toString()); 11 | 12 | const squareNumbers = []; 13 | for (let i = 1; i * i <= target; i += 1) { 14 | squareNumbers.push(i * i); 15 | } 16 | 17 | const opt = [0]; 18 | for (let i = 1; i <= target; i += 1) { 19 | let minNumber = Infinity; 20 | 21 | squareNumbers.forEach((value) => { 22 | if (opt[i - value] < minNumber) { 23 | minNumber = opt[i - value]; 24 | } 25 | }); 26 | 27 | opt.push(minNumber + 1); 28 | } 29 | 30 | console.log(opt.pop()); 31 | -------------------------------------------------------------------------------- /17626_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 50000 이하의 제곱수들을 구한다 -> 일단 300개 아래임 3 | 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const target = Number(require('fs').readFileSync(INPUT_FILE).toString()); 7 | 8 | const squareNumbers = []; 9 | for (let i = 1; i * i <= target; i += 1) { 10 | squareNumbers.push(i * i); 11 | } 12 | 13 | const opt = [0]; 14 | for (let i = 1; i <= target; i += 1) { 15 | let minNumber = Infinity; 16 | 17 | squareNumbers.forEach((value) => { 18 | if (i >= value && opt[i - value] < minNumber) { 19 | minNumber = opt[i - value]; 20 | } 21 | }); 22 | 23 | opt.push(minNumber + 1); 24 | } 25 | 26 | console.log(opt.pop()); 27 | -------------------------------------------------------------------------------- /1806.js: -------------------------------------------------------------------------------- 1 | /// 틀렸습니다 /// 2 | 3 | /* 4 | 처음 부분합의 양 끝점은 배열의 처음과 마지막 5 | 양 끝점 중 더 작은 걸 뺐을 때 부분합이 S보다 크면 뺀다 6 | */ 7 | 8 | // input 9 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 10 | const [N, S, ... arr] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(Number); 11 | 12 | // process 13 | let left = 0; 14 | let right = N - 1; 15 | let sum = arr.reduce((prev, cur) => prev + cur, 0); 16 | 17 | while (sum >= S && left < right) 18 | { 19 | if (arr[left] <= arr[right] && sum - arr[left] >= S) 20 | sum -= arr[left++]; 21 | else if (arr[left] > arr[right] && sum - arr[right] >= S) 22 | sum -= arr[right--]; 23 | else 24 | break; 25 | } 26 | 27 | // output 28 | console.log(sum >= S? right - left + 1 : 0); -------------------------------------------------------------------------------- /1806_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1. 처음 부분합의 양 끝점은 배열의 처음과 처음 3 | 2. 부분합이 S 이상이 될 때까지 오른쪽 끝점을 오른쪽으로 움직인다. 4 | 3. 이후에 왼쪽 끝을 오른쪽으로 움직여도 되는지 본다 5 | 4. 슬라이딩 윈도우로 양 끝점을 오른쪽으로 움직인다 6 | 5. 3~5 반복 7 | */ 8 | 9 | // input 10 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 11 | const [N, S, ... arr] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(Number); 12 | 13 | // process 14 | let left = 0; 15 | let right = 1; 16 | let sum = arr[0]; 17 | let found; 18 | 19 | while (sum < S && right < N) 20 | sum += arr[right++]; 21 | 22 | if (sum >= S) 23 | found = true; 24 | 25 | while (left < right && right <= N) 26 | { 27 | while (sum - arr[left] >= S && left < right - 1) 28 | { 29 | sum -= arr[left++]; 30 | } 31 | 32 | sum -= arr[left++]; 33 | sum += arr[right++]; 34 | } 35 | 36 | // output 37 | console.log(found? right - left: 0); -------------------------------------------------------------------------------- /18228.js: -------------------------------------------------------------------------------- 1 | /* 2 | 펭귄 왼쪽이랑 오른쪽에서 각각 가장 비용이 낮은거 깨기 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [, ices] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 6 | 7 | const [left, right] = ices.split('-1').map((side) => side.trim().split(' ').map(Number)); 8 | 9 | console.log(Math.min(...left) + Math.min(...right)); 10 | -------------------------------------------------------------------------------- /18398.js: -------------------------------------------------------------------------------- 1 | const INPUIT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const inputs = require('fs') 3 | .readFileSync(INPUIT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const sol = inputs 10 | .filter(([, another]) => Number.isInteger(another)) 11 | .map(([one, another]) => `${one + another} ${one * another}`); 12 | 13 | console.log(sol.join('\n')); 14 | -------------------------------------------------------------------------------- /1863.js: -------------------------------------------------------------------------------- 1 | /* 2 | 스택 3 | 4 | 고도가 바뀌는 지점 하나씩 골라서 스택에 넣어본다. 5 | 고도가 높아진다? 6 | 높아지면 무조건 새 건물이란 뜻 7 | 고도가 낮아진다? 8 | 본인보다 높은애들을 전부 빼본다 9 | 만약 스택에 본인보다 작은게 남아있으면 새로운 건물 10 | 본인과 같은 높이가 남아있으면 그 건물의 연장선이라 생각 11 | */ 12 | // input 13 | const inputFile = process.platform === 'linux' ? '/dev/stdin' : './input'; 14 | let [N, ...skyline] = require('fs').readFileSync(inputFile).toString().trim() 15 | .split('\n'); 16 | 17 | skyline = skyline.map((line) => { 18 | const coord = line.split(' ').map(Number); 19 | return coord[1]; 20 | }); 21 | 22 | // process 23 | const stack = [0]; 24 | let sol = 0; 25 | 26 | skyline.forEach((height) => { 27 | while (stack[stack.length - 1] > height) { 28 | stack.pop(); 29 | } 30 | 31 | if (stack[stack.length - 1] < height) { 32 | sol += 1; 33 | } 34 | stack.push(height); 35 | }); 36 | 37 | // output 38 | console.log(sol); 39 | -------------------------------------------------------------------------------- /18870.js: -------------------------------------------------------------------------------- 1 | /* 2 | 제일 작은 숫자를 0으로 매칭하는듯? 3 | 1. 숫자 정렬하기 4 | 2. 역으로 매핑하는 함수 만들기 5 | */ 6 | const INPUIT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const [, ...coordinate] = require('fs') 8 | .readFileSync(INPUIT_FILE) 9 | .toString() 10 | .trim() 11 | .split(/\s/) 12 | .map(Number); 13 | 14 | const values = Array.from(new Set(coordinate).values()).sort((one, another) => one - another); 15 | const compressMap = {}; 16 | values.forEach((value, index) => { 17 | compressMap[value] = index; 18 | }); 19 | 20 | const sol = coordinate.map((value) => compressMap[value]); 21 | 22 | console.log(sol.join(' ')); 23 | -------------------------------------------------------------------------------- /1919.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [A, B] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n'); 4 | 5 | const countAlphabets = (string) => { 6 | const counts = new Array(26).fill(0); 7 | 8 | string.split('').forEach((char) => { 9 | counts[char.charCodeAt(0) - 'a'.charCodeAt(0)] += 1; 10 | }); 11 | 12 | return counts; 13 | }; 14 | 15 | const arrayDifferenceCount = (arr1, arr2) => { 16 | let count = 0; 17 | 18 | arr1.forEach((value, index) => { 19 | count += Math.abs(value - arr2[index]); 20 | }); 21 | 22 | return count; 23 | }; 24 | 25 | const counts1 = countAlphabets(A); 26 | const counts2 = countAlphabets(B); 27 | 28 | console.log(arrayDifferenceCount(counts1, counts2)); 29 | -------------------------------------------------------------------------------- /1924.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [x, y] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(' ') 4 | .map(Number); 5 | 6 | const date = new Date(`2007-${x}-${y}`); 7 | const day = date.toLocaleString('en-US', { weekday: 'short' }).toUpperCase(); 8 | 9 | console.log(day); 10 | -------------------------------------------------------------------------------- /1929.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [start, end] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(' ') 4 | .map(Number); 5 | 6 | const isPrime = new Array(end + 1).fill(true); 7 | const primeNumbers = []; 8 | 9 | isPrime[0] = false; 10 | isPrime[1] = false; 11 | 12 | for (let number = 2; number <= end; number += 1) { 13 | if (isPrime[number]) { 14 | primeNumbers.push(number); 15 | 16 | for (let notPrimeNumber = number * 2; notPrimeNumber <= end; notPrimeNumber += number) { 17 | isPrime[notPrimeNumber] = false; 18 | } 19 | } 20 | } 21 | 22 | console.log(primeNumbers.filter((value) => value >= start && value <= end).join('\n')); 23 | -------------------------------------------------------------------------------- /19844.js: -------------------------------------------------------------------------------- 1 | /* 2 | 그냥 구현 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const sol = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split(/[ -]/) 10 | .map((word) => word.split(/^(?:[cjnmtsld]|qu)'[aeiouh]/)) 11 | .flat().length; 12 | 13 | console.log(sol); 14 | -------------------------------------------------------------------------------- /20309.js: -------------------------------------------------------------------------------- 1 | /* 2 | 두 숫자의 위치를 바꾸는 방식으로 정렬 3 | --> 이미 있는 방식임 4 | 5 | 근데 여기선 6 | 홀수번쨰 자리의 숫자는 홀수자리로만 이동가능 7 | 짝수도 마찬가지 8 | 9 | 배열을 정상적으로 정렬해 보고 10 | 만약 홀짝이 바뀌어야 정렬이 가능하다면 불가능 11 | 12 | 잠깐 13 | "1 이상 N 이하의 정수가 주어진 배열에 한 번씩 등장한다." 14 | 정렬할 필요조차 없음 15 | */ 16 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 17 | const [_, ...originalArray] = require('fs').readFileSync(INPUT_FILE).toString().trim() 18 | .split(/\s/) 19 | .map(Number); 20 | 21 | const canSort = originalArray.every((value, index) => (value + index + 1) % 2 === 0); 22 | 23 | console.log(canSort ? 'YES' : 'NO'); 24 | -------------------------------------------------------------------------------- /20364.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1번에서 원하는 땅 찾아가기보다 원하는 땅에서 1번 찾아가기가 더 쉬움 3 | 거꾸로 찾아가면서 만나는 가장 마지막 점유된 땅을 구하면 됨 4 | 5 | 거꾸로 찾는 시간 logN 6 | 오리의 수 Q 7 | -> QlogN 8 | */ 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [landCount, , ...wanted] = require('fs') 11 | .readFileSync(INPUT_FILE) 12 | .toString() 13 | .trim() 14 | .split(/\s/) 15 | .map(Number); 16 | 17 | const hasOwner = Array.from({ length: landCount + 1 }); 18 | const sol = []; 19 | wanted.forEach((target) => { 20 | let owner = 0; 21 | for (let current = target; current >= 1; current = Math.floor(current / 2)) { 22 | if (hasOwner[current]) { 23 | owner = current; 24 | } 25 | } 26 | 27 | if (owner === 0) { 28 | hasOwner[target] = true; 29 | } 30 | 31 | sol.push(owner); 32 | }); 33 | 34 | console.log(sol.join('\n')); 35 | -------------------------------------------------------------------------------- /20551.js: -------------------------------------------------------------------------------- 1 | /* 2 | 이분탐색 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [[length], ...inputs] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n') 10 | .map((line) => line.split(' ').map(Number)); 11 | 12 | const list = inputs 13 | .slice(0, length) 14 | .flat() 15 | .sort((a, b) => a - b); 16 | const questions = inputs.slice(length).flat(); 17 | const find = (value) => { 18 | let left = 0; 19 | let right = length; 20 | 21 | while (left < right) { 22 | const mid = Math.floor((left + right) / 2); 23 | if (list[mid] < value) { 24 | left = mid + 1; 25 | } else { 26 | right = mid; 27 | } 28 | } 29 | 30 | const hasValue = list[left] === value; 31 | return hasValue ? left : -1; 32 | }; 33 | 34 | const sol = questions.map(find); 35 | 36 | console.log(sol.join('\n')); 37 | -------------------------------------------------------------------------------- /2056.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := i번 작업 완료까지 최소 시간 3 | time(i) := i번 작업을 완료하는 데 필요한 시간 4 | opt(i) = 5 | opt(k) + time(i) 6 | 들 중 최대값. 7 | (k는 i의 선행작업) 8 | */ 9 | 10 | // input 11 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 12 | const input = require('fs').readFileSync(inputFile).toString().trim().split('\n'); 13 | 14 | const N = Number(input[0]); 15 | const time = [0]; 16 | const prev = [[]]; 17 | 18 | for (let i=1; i<=N; i++) 19 | { 20 | const [t, _, ... p] = input[i].split(' ').map(Number); 21 | time.push(t); 22 | prev.push(p); 23 | } 24 | 25 | // process 26 | const opt = [0]; 27 | for (let i=1; i<=N; i++) 28 | { 29 | let val = 0; 30 | for (let p of prev[i]) 31 | if (opt[p] > val) val = opt[p]; 32 | opt.push(val + time[i]); 33 | } 34 | 35 | // output 36 | console.log(Math.max(...opt)); -------------------------------------------------------------------------------- /2121.js: -------------------------------------------------------------------------------- 1 | /* 2 | 점 하나를 찍고 그걸 좌하단 점이라 친 다음, 나머지 세 점이 있는지 확인하면 되는 문제 3 | 점 유무는 모든 점을 set에서 관리하면 판별 가능 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, [width, height], ...points] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | const pointSet = new Set(points.map(([x, y]) => `${x} ${y}`)); 14 | let sol = 0; 15 | 16 | points.forEach(([x, y]) => { 17 | if ( 18 | pointSet.has(`${x + width} ${y}`) && 19 | pointSet.has(`${x} ${y + height}`) && 20 | pointSet.has(`${x + width} ${y + height}`) 21 | ) { 22 | sol += 1; 23 | } 24 | }); 25 | 26 | console.log(sol); 27 | -------------------------------------------------------------------------------- /2133.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3*2 크기의 벽을 딱 맞게 채우는 방법 3가지 3 | 4 | U자 컵(또는 n자 지붕) 모양 안쪽을 가로로 채우는 방식으로 5 | 3*k (k는 4이상 짝수)를 채우는 방법 k마다 2가지씩 6 | 7 | 즉 얘네들을 조립해서 3*N 크기의 벽을 만듦. 8 | 9 | 이러면 일단 N이 홀수면 불가능. 10 | 짝수인 i에 대해 11 | opt(i) = 12 | opt(i-2) * 3 13 | + sum(opt(i-k) * 2) 14 | k는 4이상 짝수, k<=i 15 | */ 16 | 17 | // input 18 | const inputFile = process.platform == 'linux'? '/dev/stdin' : './input'; 19 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 20 | 21 | // process 22 | let opt = new Array(N + 1).fill(0); 23 | opt[0] = 1; 24 | 25 | for (let i=2; i<=N; i+=2) 26 | { 27 | let sum = opt[i - 2] * 3; 28 | for (let k=4; k<=i; k+=2) 29 | sum += opt[i - k] * 2; 30 | opt[i] = sum; 31 | } 32 | 33 | // output 34 | console.log(opt[N]); -------------------------------------------------------------------------------- /21557.js: -------------------------------------------------------------------------------- 1 | /* 2 | 어차피 최후의 2인은 양쪽 끝 두 개임 3 | -> 터질때 충격파로 양쪽 끝의 높이를 갉아먹어야 함 4 | 5 | 왼쪽과 오른쪽 중 큰놈부터 하나씩 깎음 6 | 맨 마지막에는 둘다 깎임 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [fireworkCount, ...fireworks] = require('fs') 10 | .readFileSync(INPUT_FILE) 11 | .toString() 12 | .trim() 13 | .split(/\s/) 14 | .map(Number); 15 | 16 | let left = fireworks[0]; 17 | let right = fireworks[fireworkCount - 1]; 18 | 19 | for (let boom = 0; boom < fireworkCount - 3; boom += 1) { 20 | if (left < right) right -= 1; 21 | else left -= 1; 22 | } 23 | 24 | left -= 1; 25 | right -= 1; 26 | 27 | console.log(Math.max(left, right)); 28 | -------------------------------------------------------------------------------- /21966.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, target] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | if (target.length <= 25) { 5 | console.log(target); 6 | } else if (!target.slice(11, -12).includes('.')) { 7 | console.log(`${target.slice(0, 11)}...${target.slice(-11)}`); 8 | } else { 9 | console.log(`${target.slice(0, 9)}......${target.slice(-10)}`); 10 | } 11 | -------------------------------------------------------------------------------- /2204.js: -------------------------------------------------------------------------------- 1 | /* 2 | 세상에서 제일 귀찮은 입력 파싱문제 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const inputs = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 6 | 7 | inputs.pop(); 8 | 9 | const sol = []; 10 | let i = 0; 11 | 12 | while (i < inputs.length) { 13 | const length = Number(inputs[i]); 14 | i += 1; 15 | 16 | let fastest = 'Z'.repeat(100); 17 | 18 | for (let count = 0; count < length; count += 1) { 19 | if (inputs[i].toLowerCase() < fastest.toLowerCase()) fastest = inputs[i]; 20 | i += 1; 21 | } 22 | 23 | sol.push(fastest); 24 | } 25 | 26 | console.log(sol.join('\n')); 27 | -------------------------------------------------------------------------------- /2208.js: -------------------------------------------------------------------------------- 1 | /* 2 | 길이가 X 이상인 부분합 중 최댓값 찾는 문제 3 | -> 특정 구간의 부분합은 누적합으로 금방 구함 4 | 누적합 배열에서 끝점-시작점이 최대가 되려면?? 5 | -> 끝점은 가장 커야 하고 시작점은 가장 작아야 함 6 | 7 | sum(i) := 0번~i번 누적합 8 | opt(i) := i번을 끝점으로 하는 최대 구간합인데 길이가 X 이상 9 | minSum(i) := min(sum(0), ..., sum(i)) 10 | 11 | opt(i) := sum(i) - minSum(i-X) 12 | minSum(i) = min(sum(i), minSum(i-1)) 13 | */ 14 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 15 | const [, ...gems] = require('fs') 16 | .readFileSync(INPUT_FILE) 17 | .toString() 18 | .trim() 19 | .split(/\s/) 20 | .map(Number); 21 | 22 | const [minGemCount] = gems; 23 | const sum = [0]; 24 | const minSum = [0]; 25 | const opt = [-Infinity]; 26 | 27 | for (let i = 1; i < gems.length; i += 1) { 28 | sum.push(sum[i - 1] + gems[i]); 29 | minSum.push(Math.min(sum[i], minSum[i - 1])); 30 | opt.push(sum[i] - (minSum[i - minGemCount] ?? Infinity)); 31 | } 32 | 33 | const maxValue = Math.max(...opt); 34 | 35 | console.log(maxValue > 0 ? maxValue : 0); 36 | -------------------------------------------------------------------------------- /22232.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [info, ...rest] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const [, extensionCount] = info.split(' ').map(Number); 5 | const files = rest.slice(0, -extensionCount).map((line) => line.split('.')); 6 | const extensions = new Set(rest.slice(-extensionCount)); 7 | 8 | files.sort((one, another) => { 9 | if (one[0] !== another[0]) return one[0] < another[0] ? -1 : 1; 10 | 11 | if (extensions.has(one[1]) && !extensions.has(another[1])) return -1; 12 | if (!extensions.has(one[1]) && extensions.has(another[1])) return 1; 13 | 14 | return one[1] < another[1] ? -1 : 1; 15 | }); 16 | 17 | console.log(files.map((line) => line.join('.')).join('\n')); 18 | -------------------------------------------------------------------------------- /2225.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i, cnt) := 0부터 i까지 정수 cnt개를 더해 합이 i인 경우의 수 3 | opt(i, cnt) = sum( opt(i-j, cnt-1) ) 4 | j는 j<=i인 정수 5 | 6 | opt(i, cnt)계산에 opt(i, cnt-1)만 보면 되므로 7 | 2차원 배열 필요 x 8 | */ 9 | 10 | // input 11 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 12 | const [N, K] = require('fs').readFileSync(inputFile).toString().trim().split(' ').map(x => parseInt(x)); 13 | 14 | // process 15 | let prev = new Array(N + 1).fill(1); 16 | 17 | for (let k=2; k<=K; k++) 18 | { 19 | let cur = new Array(N + 1).fill(0); 20 | 21 | for (let i=0; i<=N; i++) 22 | { 23 | for (let j=0; j<=i; j++) 24 | cur[i] += prev[i - j]; 25 | } 26 | 27 | prev = cur.map(x => x % 1000000000); 28 | } 29 | 30 | // output 31 | console.log(prev[N]); -------------------------------------------------------------------------------- /22351.js: -------------------------------------------------------------------------------- 1 | /* 2 | 시작점이 1자리, 2자리, ... 일 경우부터 출발해본다. 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const writing = require('fs').readFileSync(INPUT_FILE).toString().trim(); 6 | 7 | let startValue; 8 | let endValue; 9 | 10 | for ( 11 | startValue = writing[0]; 12 | startValue.length <= writing.length; 13 | startValue += writing[startValue.length] 14 | ) { 15 | let answer = ''; 16 | endValue = Number(startValue); 17 | 18 | for (endValue = Number(startValue); answer.length < writing.length; endValue += 1) { 19 | answer += endValue.toString(); 20 | } 21 | 22 | if (answer === writing) break; 23 | } 24 | 25 | console.log(startValue, endValue - 1); 26 | -------------------------------------------------------------------------------- /2238.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const auctioneers = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .slice(1) 5 | .map((line) => line.split(' ')) 6 | .map(([name, value]) => [name, Number(value)]); 7 | 8 | const prices = {}; 9 | auctioneers.forEach(([name, value]) => { 10 | if (!Object.prototype.hasOwnProperty.call(prices, value)) { 11 | prices[value] = [0, name]; 12 | } 13 | 14 | prices[value][0] += 1; 15 | }); 16 | 17 | const [[price, [_, personName]]] = Object.entries(prices).sort((a, b) => { 18 | const aCount = a[1][0]; 19 | const aMoney = Number(a[0]); 20 | 21 | const bCount = b[1][0]; 22 | const bMoney = Number(b[0]); 23 | 24 | if (aCount !== bCount) return aCount - bCount; 25 | return aMoney - bMoney; 26 | }); 27 | 28 | console.log(personName, price); 29 | -------------------------------------------------------------------------------- /2294.js: -------------------------------------------------------------------------------- 1 | /* 2 | a, b, c 세 종류의 동전으로 i원을 만드는 방법: 3 | i-a원에서 a를 더한다. 4 | i-b원에서 b를 더한다. 5 | i-c원에서 c를 더한다. 6 | 7 | opt(i) := N종류의 동전을 최소한으로 써서 i원을 만드는 경우 8 | opt(i) = 9 | min(opt(i - x)) + 1 10 | x는 각 동전의 가치 11 | */ 12 | 13 | // input 14 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 15 | const [n, k, ... coin] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/); 16 | 17 | // process 18 | opt = new Array(k + 1); 19 | opt[0] = 0; 20 | 21 | for(let i=1; i<=k; i++) 22 | { 23 | let val = Infinity; 24 | for(let c of coin) 25 | { 26 | if(i < c || opt[i - c] == -1) 27 | continue; 28 | 29 | val = Math.min(val, opt[i - c]); 30 | } 31 | opt[i] = val != Infinity? val + 1 : -1; 32 | } 33 | 34 | // output 35 | console.log(opt[k]); -------------------------------------------------------------------------------- /2304.js: -------------------------------------------------------------------------------- 1 | /* 2 | 물이 고이지 않도록 하려면 U자형으로 지붕을 만들면 안된다. 3 | 높이 1 단위로 잘라서 본다고 했을 때 해당 높이에 지붕 뭉탱이가 두 개 이상 있다? 4 | >> 아래 높이 하나의 뭉탱이랑 이어지면 U자형이 되어서 물이 고임. 5 | 즉 각 높이별로 뭉탱이가 1개가 되도록 가장 왼쪽 기둥 ~ 가장 오른쪽 기둥을 이어야 함. 6 | */ 7 | 8 | // input 9 | const inputFile = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [[N], ...pillars] = require('fs').readFileSync(inputFile).toString().trim() 11 | .split('\n') 12 | .map((line) => line.split(' ').map(Number)); 13 | 14 | // process 15 | let sol = 0; 16 | for (let curHeight = 1; curHeight < 1000; curHeight += 1) { 17 | let left = 1001; 18 | let right = 0; 19 | 20 | pillars.forEach(([pos, pillarHeight]) => { 21 | if (pillarHeight >= curHeight) { 22 | left = Math.min(pos, left); 23 | right = Math.max(pos, right); 24 | } 25 | }); 26 | 27 | if (left === 1001) break; 28 | 29 | sol += right - left + 1; 30 | } 31 | 32 | // output 33 | console.log(sol); 34 | -------------------------------------------------------------------------------- /23322.js: -------------------------------------------------------------------------------- 1 | /* 2 | 모든 숫자의 평준화가 가능한가? 3 | 4 | 0-index 기준 5 | K번 숫자를 0번과 같게 만들면 6 | K+1번도 0번=1번과 같게 만들 수 있음 7 | 같은 방식으로 전체의 평준화 가능 8 | */ 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [, numbers] = require('fs') 11 | .readFileSync(INPUT_FILE) 12 | .toString() 13 | .trim() 14 | .split('\n') 15 | .map((line) => line.split(' ').map(Number)); 16 | 17 | let eat = 0; 18 | let count = 0; 19 | const base = numbers[0]; 20 | 21 | numbers.forEach((value) => { 22 | if (value === base) return; 23 | eat += value - base; 24 | count += 1; 25 | }); 26 | 27 | console.log(eat, count); 28 | -------------------------------------------------------------------------------- /23323.js: -------------------------------------------------------------------------------- 1 | /* 2 | 체력이 1일 때 하루에 먹이를 1씩 주면 연명 가능 3 | -> 먹이 한 개당 하루를 무조건 보장받는 방법 4 | 5 | 9 -> 4 -> 2 -> 1 6 | 8 -> 4 -> 2 -> 1 7 | 7 -> 3 -> 1 8 | 9 | 주어진 수가 2^i 이상 2^(i+1) 미만일 때 i+1일을 버티고 체력이 1이 됨 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [, ...tests] = require('fs') 13 | .readFileSync(INPUT_FILE) 14 | .toString() 15 | .trim() 16 | .split('\n') 17 | .map((line) => line.split(' ').map(Number)); 18 | 19 | const sol = []; 20 | 21 | tests.forEach(([health, food]) => { 22 | const survivingDays = health.toString(2).length; 23 | sol.push(survivingDays + food); 24 | }); 25 | 26 | console.log(sol.join('\n')); 27 | -------------------------------------------------------------------------------- /2338.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [A, B] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map(BigInt); 5 | 6 | console.log(`${A + B}\n${A - B}\n${A * B}`); 7 | -------------------------------------------------------------------------------- /23738.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const word = require('fs').readFileSync(INPUT_FILE).toString().trim(); 3 | 4 | const special = { 5 | B: 'v', 6 | E: 'ye', 7 | H: 'n', 8 | P: 'r', 9 | C: 's', 10 | Y: 'u', 11 | X: 'h', 12 | }; 13 | 14 | console.log( 15 | Array.from(word) 16 | .map((char) => special[char] ?? char.toLowerCase()) 17 | .join(''), 18 | ); 19 | -------------------------------------------------------------------------------- /23841.js: -------------------------------------------------------------------------------- 1 | /* 2 | 그림의 폭은 항상 짝수 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [info, ...drawing] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 6 | 7 | const [height, width] = info.split(' ').map(Number); 8 | 9 | const result = drawing.map((line) => Array.from(line)); 10 | 11 | for (let h = 0; h < height; h += 1) { 12 | for (let w = 0; w < width; w += 1) { 13 | if (drawing[h][w] === '.') continue; 14 | 15 | const half = (width - 1) / 2; 16 | 17 | if (w < half) result[h][width - 1 - w] = drawing[h][w]; 18 | else result[h][Math.floor(half) - (w - Math.ceil(half))] = drawing[h][w]; 19 | } 20 | } 21 | 22 | console.log(result.map((row) => row.join('')).join('\n')); 23 | -------------------------------------------------------------------------------- /23971.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [height, width, heightGap, widthGap] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(' ') 4 | .map(Number); 5 | 6 | console.log( 7 | Math.ceil(height / (heightGap + 1)) * Math.ceil(width / (widthGap + 1)), 8 | ); 9 | -------------------------------------------------------------------------------- /24183.js: -------------------------------------------------------------------------------- 1 | /* 2 | 종이의 크기 X m^2 3 | 종이의 무게 Y g/m^2 4 | 무게 XY 5 | 봉투는 종이 2장 6 | 포스터도 종이 2장 7 | 안내지는 1장 8 | */ 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [c4, a3, a4] = require('fs') 11 | .readFileSync(INPUT_FILE) 12 | .toString() 13 | .trim() 14 | .split(' ') 15 | .map(Number); 16 | 17 | const toMeters = (mm) => Number((mm / 10 / 100).toFixed(3)); 18 | const envelope = toMeters(229) * toMeters(324) * c4 * 2; 19 | const posters = toMeters(297) * toMeters(420) * a3 * 2; 20 | const info = toMeters(210) * toMeters(297) * a4; 21 | 22 | console.log((envelope + posters + info).toFixed(4)); 23 | -------------------------------------------------------------------------------- /2420.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [N, M] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(' ') 4 | .map(Number); 5 | 6 | console.log(Math.abs(N - M)); 7 | -------------------------------------------------------------------------------- /24228.js: -------------------------------------------------------------------------------- 1 | /* 2 | "종류"가 N개 3 | "최악" 4 | 5 | 일단 N뽑했는데 다 다른종류임 6 | 그럼 짝1 -> N+1뽑 7 | 짝2 -> 짝1때 뽑아서 없어진종류가 또나와 + 다시 1뽑 -> N+1+2뽑 8 | 9 | 베이스를 N-1로 깔고 한쌍당 두번씩 더뽑는다는느낌 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [N, R] = require('fs').readFileSync(INPUT_FILE).toString().trim().split(' ').map(BigInt); 13 | 14 | console.log((N - 1n + R * 2n).toString()); 15 | -------------------------------------------------------------------------------- /2428.js: -------------------------------------------------------------------------------- 1 | /* 2 | 파일 크기 오름차순 정렬 3 | 4 | 각 파일마다 5 | 본인보다 작은 파일들 검사 6 | 본인 90% 크기의 index를 찾아서 거기부터 본인까지 몇개인지 셈 7 | 8 | 이분탐색 9 | 움직이는 값: 배열의 index 10 | 기준점: 각 파일 크기의 90% 11 | 중간값 위치의 파일 크기가 기준점보다 작으면 늘리기 12 | 중간값 위치의 파일 크기가 기준점보다 크거나 같으면 줄이기 13 | */ 14 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 15 | const [, ...files] = require('fs').readFileSync(INPUT_FILE).toString().trim() 16 | .split(/\s/) 17 | .map(Number); 18 | 19 | files.sort((a, b) => a - b); 20 | 21 | const countAdjacentFiles = (index) => { 22 | const datumPoint = Math.ceil(files[index] * 0.9); 23 | 24 | let left = 0; 25 | let right = index; 26 | 27 | while (left < right) { 28 | const mid = Math.floor((left + right) / 2); 29 | 30 | if (files[mid] < datumPoint) left = mid + 1; 31 | else right = mid; 32 | } 33 | 34 | return index - left; 35 | }; 36 | 37 | const sol = files.reduce((prev, _, index) => prev + countAdjacentFiles(index), 0); 38 | 39 | console.log(sol); 40 | -------------------------------------------------------------------------------- /2438.js: -------------------------------------------------------------------------------- 1 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 2 | const N = Number(require('fs').readFileSync(inputFile).toString().trim()); 3 | 4 | let line = ''; 5 | const sol = []; 6 | for (let i=0; i { 10 | if (i === 0 || j === 0) { 11 | count += 1; 12 | } else { 13 | matrixPathRec(i - 1, j); 14 | matrixPathRec(i, j - 1); 15 | } 16 | }; 17 | matrixPathRec(n, n); 18 | 19 | console.log(count, n ** 2); 20 | -------------------------------------------------------------------------------- /24418_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 코드2: 이중for문 안에있으므로 n^2 3 | 코드1: 이건 해봐야겠는데 4 | 5 | 2 1 6 | 1 1 7 | 8 | 6 3 1 9 | 3 2 1 10 | 1 1 1 11 | 12 | 20 10 4 1 13 | 10 6 3 1 14 | 4 3 2 1 15 | 1 1 1 1 16 | 17 | 70 35 15 5 1 18 | 35 20 10 4 1 19 | 15 10 6 3 1 20 | 5 4 3 2 1 21 | 1 1 1 1 1 22 | 23 | 오른쪽 아래에서부터 시작하고 24 | 왼쪽이랑 위쪽을 본인이 불린만큼 부름 25 | */ 26 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 27 | const [n] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n').map(Number); 28 | 29 | const counts = Array.from({ length: n + 1 }).map(() => Array.from({ length: n + 1 }).fill(0)); 30 | counts[0][0] = 1; 31 | for (let r = 0; r <= n; r += 1) { 32 | for (let c = 0; c <= n; c += 1) { 33 | if (r < n) { 34 | counts[r + 1][c] += counts[r][c]; 35 | } 36 | if (c < n) { 37 | counts[r][c + 1] += counts[r][c]; 38 | } 39 | } 40 | } 41 | 42 | console.log(counts[n][n], n ** 2); 43 | -------------------------------------------------------------------------------- /24498.js: -------------------------------------------------------------------------------- 1 | /* 2 | 가장 높은 탑이 옆에걸 흡수하기 3 | 흡수는 본인 양옆에걸 하기 때문에 멀리있는 블롭을 '전달'하는건 불가 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, ...towers] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split(/\s/) 11 | .map(Number); 12 | 13 | let sol = 0; 14 | 15 | for (let i = 0; i < towers.length; i += 1) { 16 | const height = towers[i] + Math.min(towers[i - 1] ?? 0, towers[i + 1] ?? 0); 17 | sol = Math.max(height, sol); 18 | } 19 | 20 | console.log(sol); 21 | -------------------------------------------------------------------------------- /24499.js: -------------------------------------------------------------------------------- 1 | /* 2 | 슬라이딩 윈도우 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [pieCount, eatCount, ...tastyScores] = require('fs').readFileSync(INPUT_FILE).toString().trim() 6 | .split(/\s/) 7 | .map(Number); 8 | 9 | let currentTastyScore = 0; 10 | let right; 11 | 12 | for (right = 0; right < eatCount; right += 1) { 13 | currentTastyScore += tastyScores[right]; 14 | } 15 | 16 | let maxTastyScore = currentTastyScore; 17 | let left = 1; 18 | 19 | while (left !== 0) { 20 | currentTastyScore -= tastyScores[left - 1]; 21 | currentTastyScore += tastyScores[right]; 22 | 23 | if (currentTastyScore > maxTastyScore) maxTastyScore = currentTastyScore; 24 | 25 | left = (left + 1) % pieCount; 26 | right = (right + 1) % pieCount; 27 | } 28 | 29 | console.log(maxTastyScore); 30 | -------------------------------------------------------------------------------- /24511.js: -------------------------------------------------------------------------------- 1 | /* 2 | 스택: 어차피 들어온게 나가서 원래 뭐가 들어있는지 알필요없음 3 | 큐: 어차피 길이가 2임 4 | -> 스택은 무시하고 큐는 쭉 이어붙여서 하나로 만들 수 있음 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const [, info, initialValue, , sequence] = require('fs') 8 | .readFileSync(INPUT_FILE) 9 | .toString() 10 | .trim() 11 | .split('\n') 12 | .map((line) => line.split(' ').map(Number)); 13 | 14 | const q = { 15 | list: [], 16 | first: 0, 17 | length: 0, 18 | enqueue(value) { 19 | this.list.push(value); 20 | this.length += 1; 21 | }, 22 | dequeue() { 23 | if (!this.length) return null; 24 | this.first += 1; 25 | return this.list[this.first - 1]; 26 | }, 27 | }; 28 | 29 | for (let i = info.length - 1; i >= 0; i -= 1) { 30 | if (info[i] === 0) { 31 | q.enqueue(initialValue[i]); 32 | } 33 | } 34 | 35 | const sol = []; 36 | 37 | sequence.forEach((value) => { 38 | q.enqueue(value); 39 | sol.push(q.dequeue()); 40 | }); 41 | 42 | console.log(sol.join(' ')); 43 | -------------------------------------------------------------------------------- /2477.js: -------------------------------------------------------------------------------- 1 | /* 2 | 같은 방향이 두 번 나오면 거기가 밭에서 움푹 패인 부분 3 | */ 4 | // input 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[K], ...sides] = require('fs').readFileSync(INPUT_FILE).toString().trim() 7 | .split('\n') 8 | .map((line) => line.split(' ').map(Number)); 9 | 10 | // process 11 | let sol; 12 | for (let i = 0; i < 6; i += 1) { 13 | if ( 14 | sides[i][0] === sides[(i + 2) % 6][0] 15 | && sides[(i + 1) % 6][0] === sides[(i + 3) % 6][0] 16 | ) { 17 | sol = ( 18 | (sides[i][1] + sides[(i + 2) % 6][1]) * (sides[(i + 1) % 6][1] + sides[(i + 3) % 6][1]) 19 | - (sides[(i + 1) % 6][1] * sides[(i + 2) % 6][1]) 20 | ); 21 | break; 22 | } 23 | } 24 | sol *= K; 25 | 26 | // output 27 | console.log(sol); 28 | -------------------------------------------------------------------------------- /25045.js: -------------------------------------------------------------------------------- 1 | /* 2 | 모든 기업이 거래를 하긴 함? ㄴㄴ 3 | 4 | 그리디 5 | 6 | 최종 거래 형태가 아래와 같다고 치자 7 | 만족: A, B, C, D, E 8 | 가격: a, b, c, d, e 9 | 10 | (A+B+C+...)-(a+b+c+...) 가 최대여야 함 11 | 12 | 만족도가 큰 물건부터 13 | 돈을 적게 내는 기업부터 14 | 만약 만족도-돈=0이 되는 조합이 생기면 정지 15 | 16 | JS Number는 15자리부터 위험 17 | 답은 최대 14자리 18 | */ 19 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 20 | const [, items, companies] = require('fs') 21 | .readFileSync(INPUT_FILE) 22 | .toString() 23 | .trim() 24 | .split('\n') 25 | .map((line) => line.split(' ').map(Number)); 26 | 27 | items.sort((one, another) => one - another); 28 | companies.sort((one, another) => another - one); 29 | 30 | let sol = 0; 31 | 32 | while (items.length && companies.length) { 33 | const item = items.pop(); 34 | const company = companies.pop(); 35 | 36 | if (item <= company) break; 37 | sol += item - company; 38 | } 39 | 40 | console.log(sol); 41 | -------------------------------------------------------------------------------- /25083.js: -------------------------------------------------------------------------------- 1 | console.log( 2 | " ,r'\"7\nr`-_ ,' ,/\n \\. \". L_r'\n `~\\/\n |\n |" 3 | ); -------------------------------------------------------------------------------- /2525.js: -------------------------------------------------------------------------------- 1 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 2 | let [H, M, time] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(Number); 3 | 4 | M += time; 5 | H += parseInt(M / 60); 6 | M %= 60; 7 | H %= 24; 8 | 9 | console.log(H, M); -------------------------------------------------------------------------------- /2530.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [hh, mm, ss, time] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split(/\s/) 7 | .map(Number); 8 | 9 | let hour = hh; 10 | let minute = mm; 11 | let second = ss + time; 12 | 13 | minute += Math.floor(second / 60); 14 | second %= 60; 15 | 16 | hour += Math.floor(minute / 60); 17 | minute %= 60; 18 | 19 | hour %= 24; 20 | 21 | console.log(hour, minute, second); 22 | -------------------------------------------------------------------------------- /25304.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const input = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n'); 4 | 5 | const totalPrice = Number(input[0]); 6 | const items = input.slice(2).map((line) => line.split(' ').map(Number)); 7 | 8 | const calculatedPrice = items.reduce( 9 | (previousPrice, [price, amount]) => previousPrice + price * amount, 10 | 0, 11 | ); 12 | 13 | console.log(totalPrice === calculatedPrice ? 'Yes' : 'No'); 14 | -------------------------------------------------------------------------------- /25421.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i, last) := i자리면서 일의 자리가 last인 정수 A의 개수 3 | opt(i, last) = sum( 4 | opt(i-1, last-2), 5 | opt(i-1, last-1), 6 | opt(i-1, last), 7 | opt(i-1, last+1), 8 | opt(i-1, last+2), 9 | ) 10 | 11 | opt(i, ?) 계산에 opt(i-1, ?)만 필요하므로 일차원 배열로 가능 12 | */ 13 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 14 | const maxDigit = Number(require('fs').readFileSync(INPUT_FILE).toString()); 15 | 16 | const DIVISOR = 987_654_321; 17 | 18 | let current = new Array(10).fill(1); 19 | current[0] = 0; 20 | 21 | for (let digit = 2; digit <= maxDigit; digit += 1) { 22 | const next = new Array(10); 23 | next[0] = 0; 24 | 25 | for (let i = 1; i < 10; i += 1) { 26 | next[i] = ( 27 | (current[i - 2] ?? 0) 28 | + (current[i - 1] ?? 0) 29 | + current[i] 30 | + (current[i + 1] ?? 0) 31 | + (current[i + 2] ?? 0) 32 | ) % DIVISOR; 33 | } 34 | 35 | current = next; 36 | } 37 | 38 | console.log(current.reduce((prev, cur) => (prev + cur) % DIVISOR, 0)); 39 | -------------------------------------------------------------------------------- /2558.js: -------------------------------------------------------------------------------- 1 | const input = require("fs").readFileSync("/dev/stdin").toString().trim().split('\n'); 2 | let A = parseInt(input[0]); 3 | let B = parseInt(input[1]); 4 | let sol = A + B; 5 | console.log(sol); -------------------------------------------------------------------------------- /2563.js: -------------------------------------------------------------------------------- 1 | /* 2 | 도화지가 100*100이므로 그냥 배열 만들어서 색칠하면 끝 3 | 도화지가 처음으로 색칠될 때 넓이를 더해주면 됨. 4 | */ 5 | const PAPER_SIZE = 100; 6 | const COLORED_PAPER_SIZE = 10; 7 | // input 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [[N], ...positions] = require('fs').readFileSync(INPUT_FILE).toString().trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | // process 14 | const paper = Array.from(new Array(PAPER_SIZE), () => new Array(PAPER_SIZE).fill(0)); 15 | let sol = 0; 16 | positions.forEach(([col, row]) => { 17 | for (let r = row; r < row + COLORED_PAPER_SIZE; r += 1) { 18 | for (let c = col; c < col + COLORED_PAPER_SIZE; c += 1) { 19 | paper[r][c] += 1; 20 | if (paper[r][c] === 1) sol += 1; 21 | } 22 | } 23 | }); 24 | 25 | // output 26 | console.log(sol); 27 | -------------------------------------------------------------------------------- /25630.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, skewer] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const lastIndex = skewer.length - 1; 5 | let count = 0; 6 | 7 | for (let i = 0; i <= lastIndex / 2; i += 1) { 8 | if (skewer[i] !== skewer[lastIndex - i]) count += 1; 9 | } 10 | 11 | console.log(count); 12 | -------------------------------------------------------------------------------- /25631.js: -------------------------------------------------------------------------------- 1 | /* 2 | 9 8 7 7 6 5 4 4 3 2 2 2 1 3 | 4 | 9 8 7 6 5 4 3 2 1 5 | 7 4 2 6 | 2 7 | 8 | 가장 많이 등장한 숫자의 등장 횟수? 9 | */ 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [_, ...matryoshkaList] = require('fs').readFileSync(INPUT_FILE).toString().trim() 12 | .split(/\s/) 13 | .map(Number); 14 | 15 | const counts = {}; 16 | 17 | matryoshkaList.forEach((size) => { 18 | if (!counts[size]) counts[size] = 0; 19 | counts[size] += 1; 20 | }); 21 | 22 | console.log(Math.max(...Object.values(counts))); 23 | -------------------------------------------------------------------------------- /25642.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | let [yt, yj] = require('fs').readFileSync(INPUT_FILE).toString().trim().split(' ').map(Number); 3 | 4 | let isYtTurn = true; 5 | 6 | while (yt < 5 && yj < 5) { 7 | if (isYtTurn) yj += yt; 8 | else yt += yj; 9 | 10 | isYtTurn = !isYtTurn; 11 | } 12 | 13 | console.log(isYtTurn ? 'yj' : 'yt'); 14 | -------------------------------------------------------------------------------- /25704.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [coupon, price] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map(Number); 8 | 9 | const getCouponType = (couponCount) => { 10 | return Math.min(Math.floor(couponCount / 5), 4); 11 | }; 12 | const discountFunctions = [ 13 | (value) => value, 14 | (value) => Math.max(value - 500, 0), 15 | (value) => value * 0.9, 16 | (value) => Math.max(value - 2000, 0), 17 | (value) => value * 0.75, 18 | ]; 19 | 20 | const prices = discountFunctions 21 | .filter((_, index) => index <= getCouponType(coupon)) 22 | .map((fn) => fn(price)); 23 | 24 | console.log(Math.min(...prices)); 25 | -------------------------------------------------------------------------------- /25706.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := i번 칸에서 출발했을 때 밟는 칸의 수 3 | height(i) := i번 칸 점프대의 높이 4 | opt(i) = opt(i + height(i) + 1) + 1 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const [length, ...jumpPads] = require('fs').readFileSync(INPUT_FILE).toString().trim() 8 | .split(/\s/) 9 | .map(Number); 10 | 11 | const counts = new Array(length); 12 | 13 | for (let i = length - 1; i >= 0; i -= 1) { 14 | counts[i] = 1 + (counts[i + jumpPads[i] + 1] ?? 0); 15 | } 16 | 17 | console.log(counts.join(' ')); 18 | -------------------------------------------------------------------------------- /25709.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1을 지울 수 있다면 지우는 게 무조건 좋은가? 3 | 숫자는 획기적으로 줄이긴 함 4 | 5 | 일단 1을 다 없애고 시작 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const target = require('fs').readFileSync(INPUT_FILE).toString(); 9 | 10 | const removeOne = (value) => Number(value.toString().split('1').join('')); 11 | 12 | let value = removeOne(target); 13 | let operationCount = target.length - target.replaceAll('1', '').length; 14 | 15 | while (value > 0) { 16 | if (value.toString().includes('1')) { 17 | value = removeOne(value); 18 | } else { 19 | value -= 1; 20 | } 21 | operationCount += 1; 22 | } 23 | 24 | console.log(operationCount); 25 | -------------------------------------------------------------------------------- /25757.js: -------------------------------------------------------------------------------- 1 | /* 2 | 구현 3 | set으로 중복인원 제거 4 | 플레이 인원수에는 항상 임스를 포함시켜야 함 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | let [players, game, ...names] = require('fs').readFileSync(INPUT_FILE).toString().trim() 8 | .split(/\s/); 9 | 10 | names = new Set(names); 11 | if (game === 'Y') game = 1; 12 | else if (game === 'F') game = 2; 13 | else if (game === 'O') game = 3; 14 | 15 | console.log(Math.floor(names.size / game)); 16 | -------------------------------------------------------------------------------- /2579.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i, k) := i번 계단까지 도착하는데 직전에 연속으로 밟은 계단이 k개일 경우 최대 점수 3 | score(i) := i번 계단의 점수 4 | 5 | opt(i, 2) = opt(i-1, 1) + score(i) 6 | opt(i, 1) = max(opt(i-2, 1), opt(i-2, 2)) + score(i) 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const scores = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n').map(Number); 10 | 11 | const continuous = [0, scores[1]]; 12 | const discontinuous = [0, scores[1]]; 13 | 14 | for (let i = 2; i < scores.length; i += 1) { 15 | continuous.push(discontinuous[i - 1] + scores[i]); 16 | discontinuous.push(Math.max(discontinuous[i - 2], continuous[i - 2]) + scores[i]); 17 | } 18 | 19 | console.log(Math.max(continuous.pop(), discontinuous.pop())); 20 | -------------------------------------------------------------------------------- /2591.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 앞에서 i개의 숫자를 만들 수 있는 배열의 수 3 | opt(i) = 4 | opt(i-1) 5 | i번째 숫자가 0이 아니어야 함 6 | opt(i-2) 7 | i-1번째 숫자가 0이 아니어야 함 8 | i-1번째 숫자와 i번째 숫자를 이은 값이 카드풀에 있어야 함 9 | 이 값들의 합 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const numbers = require('fs').readFileSync(INPUT_FILE).toString().trim(); 13 | 14 | const opt = [1, Number(`${numbers[0]}${numbers[1]}`) <= 34 && numbers[1] !== '0' ? 2 : 1]; 15 | 16 | for (let i = 2; i < numbers.length; i += 1) { 17 | const value1 = numbers[i] !== '0' ? opt[i - 1] : 0; 18 | const value2 = 19 | numbers[i - 1] !== '0' && Number(`${numbers[i - 1]}${numbers[i]}`) <= 34 ? opt[i - 2] : 0; 20 | opt.push(value1 + value2); 21 | } 22 | 23 | console.log(opt[numbers.length - 1]); 24 | -------------------------------------------------------------------------------- /25915.js: -------------------------------------------------------------------------------- 1 | /* 2 | 예제 2에서 I부터 시작하면 84거리가 나옴을 알 수 있음 3 | 즉 시작점부터 I까지의 거리만 알면 됨 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const start = require('fs').readFileSync(INPUT_FILE).toString().trim(); 7 | 8 | const startDistance = Math.abs(start.charCodeAt(0) - 'I'.charCodeAt(0)); 9 | console.log(startDistance + 84); 10 | -------------------------------------------------------------------------------- /25916.js: -------------------------------------------------------------------------------- 1 | /* 2 | 수열에서 연속된 구간합 중 M 이하면서 최대인 값 찾기 3 | >> 슬라이딩 윈도우 4 | 5 | 햄스터 오른쪽 끝을 한칸 늘림 6 | M보다 커지면 이하가 될 때까지 왼쪽 끝을 줄임 7 | 반복 8 | */ 9 | // input 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [holeCount, maxSize, ...holes] = require('fs').readFileSync(INPUT_FILE).toString().trim() 12 | .split(/\s/) 13 | .map(Number); 14 | 15 | // process 16 | let curSize = 0; 17 | let left = 0; 18 | let right = -1; 19 | let possibleMaxSize = 0; 20 | 21 | while (right <= holeCount) { 22 | right += 1; 23 | curSize += holes[right]; 24 | 25 | while (curSize > maxSize && left <= right) { 26 | curSize -= holes[left]; 27 | left += 1; 28 | } 29 | 30 | if (curSize > possibleMaxSize) possibleMaxSize = curSize; 31 | } 32 | 33 | // output 34 | console.log(possibleMaxSize); 35 | -------------------------------------------------------------------------------- /25917.js: -------------------------------------------------------------------------------- 1 | /* 2 | 서로 다른 소수 3 | >> 각 행의 가중치가 서로 같은(겹치는) 일이 절대 없음 4 | 5 | i번째 행의 가중치가 P_i번째에 위치... 6 | >> 그냥 각 행의 가중치를 구한다음에 순서만 바꿔주면 되므로 의미없음 7 | 8 | 결국 정답은 총 R개 행의 가중치를 만드는 경우의 수 9 | R*C개중 C개를 순서대로 배치 10 | R*C-C개중 C개를 순서대로 배치 11 | R*C-C-C개중 C개를 순서대로 배치 12 | ... 를 모두 곱한 값 13 | 여기에 각 행의 순서는 의미가 없으므로 R!개로 나눠줌 14 | === (R*C)! / R! 15 | */ 16 | const DIVISOR = 998_244_353; 17 | 18 | // input 19 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 20 | const [[R, C], ...trash] = require('fs').readFileSync(INPUT_FILE).toString().trim() 21 | .split('\n') 22 | .map((line) => line.split(' ').map(Number)); 23 | 24 | // process 25 | let sol = 1; 26 | for (let i = R + 1; i <= R * C; i += 1) sol = (sol * i) % DIVISOR; 27 | 28 | // output 29 | console.log(sol); 30 | -------------------------------------------------------------------------------- /25918.js: -------------------------------------------------------------------------------- 1 | /* 2 | 주어진 입력에 대해서 ()와 )(를 다시 합치는 문제 3 | 합칠 수 있으면 무조건 합쳐야 최소 일수가 나옴 4 | 스택을 이용해서 합칠 수 없으면 쌓음 5 | >> 합쳐질 때 쌓여있는 개수가 곧 여기까지 오는데 필요한 날짜 수 6 | 마지막에 스택이 비어있지 않다면 불가능하다는 뜻 7 | */ 8 | // input 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [N, S] = require('fs').readFileSync(INPUT_FILE).toString().trim() 11 | .split('\n'); 12 | 13 | // process 14 | let sol = 0; 15 | const stack = []; 16 | 17 | for (let i = 0; i < N; i += 1) { 18 | if ((stack[stack.length - 1] === '(' && S[i] === ')') 19 | || (stack[stack.length - 1] === ')' && S[i] === '(')) { 20 | sol = Math.max(stack.length, sol); 21 | stack.pop(); 22 | } else { 23 | stack.push(S[i]); 24 | } 25 | } 26 | 27 | // output 28 | console.log(stack.length === 0 ? sol : -1); 29 | -------------------------------------------------------------------------------- /25921.js: -------------------------------------------------------------------------------- 1 | /* 2 | 소수가 아닌 사람은 본인을 소인수분해했을 때 나오는 가장 작은 소인수랑 먹으면 됨 3 | 이러면 1번과 소수끼리만 아는 사이가 되면 된다 4 | 2번은 1번이랑, 3번은 2번이랑, 5번은 3번이랑, 7번은 5번이랑, ... 이렇게해서 본인과 본인 직전 소수랑 먹으면 5 | 기차놀이처럼 서로 연결 가능 6 | >> 결국 모든 소수는 자기 자신만큼의 비용을 지불하고 먹으면 됨 7 | 8 | 결국 해야 할 건? 9 | 에라토스테네스의 체를 돌면서 본인을 죽인 가장 작은 소수를 기억 10 | */ 11 | // input 12 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 13 | const N = Number(require('fs').readFileSync(INPUT_FILE).toString()); 14 | 15 | // process 16 | const sieve = new Array(N + 1); 17 | let sol = 0; 18 | 19 | const killMultiple = (number) => { 20 | for (let victim = number; victim <= N; victim += number) { 21 | if (!sieve[victim]) { 22 | sieve[victim] = true; 23 | sol += number; 24 | } 25 | } 26 | }; 27 | 28 | for (let number = 2; number <= N; number += 1) { 29 | if (!sieve[number]) killMultiple(number); 30 | } 31 | 32 | // output 33 | console.log(sol); 34 | -------------------------------------------------------------------------------- /25966.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[row, col, queryCount], ...input] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map((line) => line.split(' ').map(Number)); 5 | 6 | const array = input.slice(0, row); 7 | const queries = input.slice(row); 8 | 9 | const change = (r, c, value) => { array[r][c] = value; }; 10 | 11 | const swap = (row1, row2) => { 12 | const temp = array[row1]; 13 | array[row1] = array[row2]; 14 | array[row2] = temp; 15 | }; 16 | 17 | const operate = (operator, i, j, k) => { 18 | if (operator === 0) change(i, j, k); 19 | else swap(i, j); 20 | }; 21 | 22 | queries.forEach(([operator, ...args]) => operate(operator, ...args)); 23 | 24 | console.log(array.map((row) => row.join(' ')).join('\n')); 25 | -------------------------------------------------------------------------------- /25972.js: -------------------------------------------------------------------------------- 1 | /* 2 | 스택 3 | 가장 오른쪽의 넘어진 도미노의 영향범위 기억 4 | 만약 영향을 받으면 stack top update 5 | 아니면 스택에 새로 삽입 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const [, ...dominoes] = require('fs') 9 | .readFileSync(INPUT_FILE) 10 | .toString() 11 | .trim() 12 | .split('\n') 13 | .map((line) => line.split(' ').map(Number)); 14 | 15 | dominoes.sort((a, b) => a[0] - b[0]); 16 | 17 | const stack = []; 18 | 19 | dominoes.forEach(([start, size]) => { 20 | if ((stack.at(-1) ?? Infinity) >= start) { 21 | stack.pop(); 22 | } 23 | stack.push(start + size); 24 | }); 25 | 26 | console.log(stack.length); 27 | -------------------------------------------------------------------------------- /25991.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...values] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split(/\s/) 7 | .map(Number); 8 | 9 | const size = values.reduce((prev, cur) => prev + cur ** 3, 0); 10 | const sol = Math.cbrt(size); 11 | 12 | console.log(sol); 13 | -------------------------------------------------------------------------------- /26069.js: -------------------------------------------------------------------------------- 1 | /* 2 | 순수 구현 3 | 무지개댄스 추는사람들의 집합 사용 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, ...meetings] = require('fs').readFileSync(INPUT_FILE).toString().trim() 7 | .split('\n') 8 | .map((line) => line.split(' ')); 9 | 10 | const dancingPeople = new Set(['ChongChong']); 11 | 12 | meetings.forEach(([one, another]) => { 13 | if (dancingPeople.has(one)) dancingPeople.add(another); 14 | else if (dancingPeople.has(another)) dancingPeople.add(one); 15 | }); 16 | 17 | console.log(dancingPeople.size); 18 | -------------------------------------------------------------------------------- /2631.js: -------------------------------------------------------------------------------- 1 | /* 2 | 누굴 옮겨야 하는가? 3 | 오름차순을 지키지 않은 애들 4 | 5 | 옮기는 수가 적으려면 어떻게? 6 | 오름차순을 지키는 애들 최대 7 | 8 | >> 가장 긴 증가하는 부분 수열 문제 9 | 10 | seq(i) := i번째 수열의 숫자 11 | opt(i) := 앞에서부터 i개 중 가장~수열의 길이 12 | opt(i) = max(opt(k) + 1) 13 | k s.trimEnd()); 5 | const line2 = ['0 0', ' 1', ' 2', ' 3', '4 4', '5 ', '6 ', ' 7', '8 8', '9 9'].map((s) => s.trimEnd()); 6 | const line3 = ['0 0', ' 1', '2222', '3333', '4444', '5555', '6666', ' 7', '8888', '9999'].map((s) => s.trimEnd()); 7 | const line4 = ['0 0', ' 1', '2 ', ' 3', ' 4', ' 5', '6 6', ' 7', '8 8', ' 9'].map((s) => s.trimEnd()); 8 | const line5 = ['0000', ' 1', '2222', '3333', ' 4', '5555', '6666', ' 7', '8888', ' 9'].map((s) => s.trimEnd()); 9 | const getDigit = (value) => { 10 | return [line1[value], line2[value], line3[value], line4[value], line5[value]].join('\n'); 11 | }; 12 | 13 | console.log(Array.from(target).map(getDigit).join('\n\n')); 14 | -------------------------------------------------------------------------------- /26530.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...inputs] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | let i = 0; 5 | const sol = []; 6 | 7 | while (i < inputs.length) { 8 | const count = Number(inputs[i]); 9 | let sum = 0; 10 | for (let j = 0; j < count; j += 1) { 11 | const [, price, count] = inputs[i + 1 + j].split(' ').map(Number); 12 | sum += price * count; 13 | } 14 | sol.push(sum); 15 | i += count + 1; 16 | } 17 | 18 | console.log(sol.map((value) => `$${value.toFixed(2)}`).join('\n')); 19 | -------------------------------------------------------------------------------- /26575.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...data] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const prices = []; 10 | 11 | data.forEach(([dogCount, neededFood, price]) => { 12 | prices.push((dogCount * neededFood * price).toFixed(2)); 13 | }); 14 | 15 | console.log(prices.map((price) => `$${price}`).join('\n')); 16 | -------------------------------------------------------------------------------- /26596.js: -------------------------------------------------------------------------------- 1 | /* 2 | 25_000_000 << 완탐가능 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [, ...inputs] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n') 10 | .map((line) => line.split(' ')); 11 | 12 | const ingredients = Array.from( 13 | inputs 14 | .reduce((result, [name, amount]) => { 15 | result.set(name, (result.get(name) ?? 0) + Number(amount)); 16 | return result; 17 | }, new Map()) 18 | .values(), 19 | ); 20 | 21 | const hasGoldenRatio = () => { 22 | for (let i = 0; i < ingredients.length; i += 1) { 23 | for (let j = i + 1; j < ingredients.length; j += 1) { 24 | if ( 25 | Math.floor(ingredients[i] * 1.618) === ingredients[j] || 26 | ingredients[i] === Math.floor(ingredients[j] * 1.618) 27 | ) { 28 | return true; 29 | } 30 | } 31 | } 32 | return false; 33 | }; 34 | 35 | console.log(hasGoldenRatio() ? 'Delicious!' : 'Not Delicious...'); 36 | -------------------------------------------------------------------------------- /2666.js: -------------------------------------------------------------------------------- 1 | /* 2 | 초기 문 2개 3 | 벽장을 사용할 때마다 두 문 중 하나를 움직임 4 | >> 총 2^20가지 경우의 수: 완전탐색 가능 5 | */ 6 | 7 | // input 8 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 9 | const [_, door1, door2, __, ... use] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(Number); 10 | 11 | // process 12 | let prev = [new State(door1, door2, 0)]; 13 | 14 | for (let u of use) 15 | { 16 | const cur = []; 17 | 18 | for (let p of prev) 19 | { 20 | // door1을 움직임 21 | cur.push(new State(u, p.door2, p.move + Math.abs(u - p.door1))); 22 | // door2를 움직임 23 | cur.push(new State(p.door1, u, p.move + Math.abs(u - p.door2))); 24 | } 25 | 26 | prev = cur; 27 | } 28 | 29 | let sol = Infinity; 30 | for (let state of prev) 31 | sol = Math.min(sol, state.move); 32 | 33 | // output 34 | console.log(sol); 35 | 36 | // function 37 | function State(door1, door2, move) 38 | { 39 | this.door1 = door1; 40 | this.door2 = door2; 41 | this.move = move; 42 | } -------------------------------------------------------------------------------- /2675.js: -------------------------------------------------------------------------------- 1 | const repeat = (count, string) => { 2 | const result = []; 3 | string.split('').forEach((char) => { 4 | for (let i = 0; i < count; i += 1) result.push(char); 5 | }); 6 | return result.join(''); 7 | }; 8 | 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [T, ...tests] = require('fs').readFileSync(INPUT_FILE).toString().trim() 11 | .split('\n') 12 | .map((line) => line.split(' ')); 13 | 14 | const sol = tests.map(([R, S]) => repeat(Number(R), S)); 15 | 16 | console.log(sol.join('\n')); 17 | -------------------------------------------------------------------------------- /2685.js: -------------------------------------------------------------------------------- 1 | // .toString() 의 인수가 2~36까지라 실패. 2 | 3 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 4 | const [, ...tests] = require('fs') 5 | .readFileSync(INPUT_FILE) 6 | .toString() 7 | .trim() 8 | .split('\n') 9 | .map((line) => line.split(' ').map(Number)); 10 | 11 | const nim = (b, x, y) => { 12 | const xBaseB = x.toString(b); 13 | const yBaseB = y.toString(b); 14 | const longerLength = Math.max(xBaseB, yBaseB); 15 | const xPadded = Array.from(xBaseB.padStart(longerLength, '0')).map(Number); 16 | const yPadded = Array.from(yBaseB.padStart(longerLength, '0')).map(Number); 17 | const nimSum = []; 18 | for (let i = 0; i < longerLength; i += 1) { 19 | nimSum.push((xPadded[i] + yPadded[i]) % b); 20 | } 21 | return parseInt(nimSum.join(''), b); 22 | }; 23 | 24 | const sol = tests.map(nim); 25 | 26 | console.log(sol.join('\n')); 27 | -------------------------------------------------------------------------------- /27159.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...cards] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split(/\s/) 7 | .map(Number); 8 | 9 | const hasCard = new Array(36).fill(false); 10 | 11 | cards.forEach((value) => { 12 | hasCard[value] = true; 13 | }); 14 | 15 | let sol = 0; 16 | let isContinuous = false; 17 | 18 | for (let i = 3; i <= 35; i += 1) { 19 | if (hasCard[i] && !isContinuous) { 20 | sol += i; 21 | isContinuous = true; 22 | } else if (!hasCard[i]) { 23 | isContinuous = false; 24 | } 25 | } 26 | 27 | console.log(sol); 28 | -------------------------------------------------------------------------------- /27161.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...cards] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ')); 8 | 9 | let hour = 1; 10 | let direction = 1; 11 | 12 | const setNextHour = () => { 13 | hour = (hour + 12 + direction) % 12; 14 | if (hour === 0) hour = 12; 15 | }; 16 | const sol = []; 17 | 18 | cards.forEach(([drawing, value]) => { 19 | const cardHour = Number(value); 20 | 21 | if (drawing === 'HOURGLASS') { 22 | sol.push(`${hour} NO`); 23 | if (cardHour !== hour) direction = -direction; 24 | } else { 25 | sol.push(`${hour} ${cardHour === hour ? 'YES' : 'NO'}`); 26 | } 27 | 28 | setNextHour(); 29 | }); 30 | 31 | console.log(sol.join('\n')); 32 | -------------------------------------------------------------------------------- /27277.js: -------------------------------------------------------------------------------- 1 | // 틀렸습니다 2 | 3 | /* 4 | 고수가 본인의 실력을 가장 많이 발휘할 수 있는 환경 5 | -> 고수 앞에는 제일 못하는 사람 6 | 7 | 못하는 사람은 실력합을 애초에 벌기 힘듦 8 | -> 못하는 사람 앞에 고수 둬서 버림패로 9 | 10 | 첫 사람은 제 실력 발휘 가능 11 | -> 초고수를 맨 앞에 12 | */ 13 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 14 | const [, ...abilities] = require('fs') 15 | .readFileSync(INPUT_FILE) 16 | .toString() 17 | .trim() 18 | .split(/\s/) 19 | .map(Number); 20 | 21 | abilities.sort((a, b) => a - b); 22 | 23 | let left = 0; 24 | let flag = true; 25 | const orders = [0]; 26 | 27 | while (left < abilities.length) { 28 | if (flag) { 29 | orders.push(abilities.pop()); 30 | } else { 31 | orders.push(abilities[left]); 32 | left += 1; 33 | } 34 | 35 | flag = !flag; 36 | } 37 | 38 | const { sum } = orders.reduce( 39 | ({ prevValue, sum }, cur) => ({ 40 | prevValue: cur, 41 | sum: sum + Math.max(0, cur - prevValue), 42 | }), 43 | { prevValue: 0, sum: 0 }, 44 | ); 45 | 46 | console.log(sum); 47 | -------------------------------------------------------------------------------- /27310.js: -------------------------------------------------------------------------------- 1 | const target = require('fs').readFileSync(0, 'utf-8').toString().trim(); 2 | 3 | const underscoreCount = Array.from(target).filter((char) => char === '_').length; 4 | const sol = target.length + 2 + underscoreCount * 5; 5 | 6 | console.log(sol); 7 | -------------------------------------------------------------------------------- /2738.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[row, col], ...inputs] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map((line) => line.split(' ').map(Number)); 5 | 6 | const A = inputs.slice(0, row); 7 | const B = inputs.slice(row); 8 | 9 | for (let r = 0; r < row; r += 1) { 10 | for (let c = 0; c < col; c += 1) { 11 | A[r][c] += B[r][c]; 12 | } 13 | } 14 | 15 | const sol = []; 16 | A.forEach((line) => sol.push(line.join(' '))); 17 | 18 | console.log(sol.join('\n')); 19 | -------------------------------------------------------------------------------- /2740.js: -------------------------------------------------------------------------------- 1 | /* 2 | 그냥 곱하면 된다. 3 | */ 4 | 5 | // input 6 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 7 | const input = require('fs').readFileSync(inputFile).toString().trim().split('\n'); 8 | 9 | const [N, M] = input[0].split(' ').map(Number); 10 | const A = []; 11 | for (let i=1; i<=N; i++) 12 | A.push(input[i].split(' ').map(Number)); 13 | const [_, K] = input[N + 1].split(' ').map(Number); 14 | const B = []; 15 | for (let i=N+2; i new Array(K).fill(0)); 20 | for (let i=0; i N - index); 5 | 6 | console.log(sol.join('\n')); 7 | -------------------------------------------------------------------------------- /2744.js: -------------------------------------------------------------------------------- 1 | const isUpperCase = (char) => /^[A-Z]$/.test(char); 2 | 3 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 4 | const input = require('fs').readFileSync(INPUT_FILE).toString().trim() 5 | .split(''); 6 | 7 | const sol = []; 8 | input.forEach((char) => { 9 | if (isUpperCase(char)) sol.push(char.toLowerCase()); 10 | else sol.push(char.toUpperCase()); 11 | }); 12 | 13 | console.log(sol.join('')); 14 | -------------------------------------------------------------------------------- /27465.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1은 1 3 | 2와 3은 4 4 | 짝수는 본인이 정답 5 | 홀수는 소수면 본인+1이 정답 6 | 7 | 이 아니라 8 | '아무거나' 출력하는 거니까 10^9 출력 9 | */ 10 | console.log(1_000_000_000); 11 | -------------------------------------------------------------------------------- /27466.js: -------------------------------------------------------------------------------- 1 | // 아 v-flag 지원안해주네 ㅋㅋ 2 | 3 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 4 | const [, targetLengthString, inputString] = require('fs') 5 | .readFileSync(INPUT_FILE) 6 | .toString() 7 | .trim() 8 | .split(/\s/); 9 | 10 | const targetLength = Number(targetLengthString); 11 | const regex = /^(?.*)A.*A(?[[A-Z]--[AEIOU]]).*$/v; 12 | const matchResult = inputString.match(regex); 13 | const result = 14 | matchResult !== null 15 | ? `${matchResult.groups.prefix.slice(-targetLength + 3)}AA${matchResult.groups.suffix}` 16 | : ''; 17 | 18 | if (result.length !== targetLength) { 19 | console.log('NO'); 20 | } else { 21 | console.log('YES'); 22 | console.log(result); 23 | } 24 | -------------------------------------------------------------------------------- /27466_v2.js: -------------------------------------------------------------------------------- 1 | // 아 v-flag 지원안해주네 ㅋㅋ 2 | 3 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 4 | const [, targetLengthString, inputString] = require('fs') 5 | .readFileSync(INPUT_FILE) 6 | .toString() 7 | .trim() 8 | .split(/\s/); 9 | 10 | const targetLength = Number(targetLengthString); 11 | const regex = /^(?.*)A.*A(?[BCDFGHJKLMNPQRSTVWXYZ]).*$/; 12 | const matchResult = inputString.match(regex); 13 | const result = 14 | matchResult !== null 15 | ? `${matchResult.groups.prefix.slice(-targetLength + 3)}AA${matchResult.groups.suffix}` 16 | : ''; 17 | 18 | if (result.length !== targetLength) { 19 | console.log('NO'); 20 | } else { 21 | console.log('YES'); 22 | console.log(result); 23 | } 24 | -------------------------------------------------------------------------------- /2748.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const n = Number(require('fs').readFileSync(INPUT_FILE).toString()); 3 | 4 | const fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597].map(BigInt); 5 | 6 | for (let i = fibo.length; i <= n; i += 1) { 7 | fibo.push(fibo[i - 1] + fibo[i - 2]); 8 | } 9 | 10 | console.log(fibo[n].toString()); 11 | -------------------------------------------------------------------------------- /27522.js: -------------------------------------------------------------------------------- 1 | /* 2 | 각 팀원의 순위 점수의 합계가 높은 팀이 승리 3 | 합계가 같다면 최고 순위가 가장 높은 팀이 승리 4 | 8명의 레이서가 모두 서로 다른 시각에 완주한 경우 순위 점수의 합계가 반드시 다르다. 5 | 모든 레이서가 반드시 서로 다른 시각에 완주한다. 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const results = require('fs') 9 | .readFileSync(INPUT_FILE) 10 | .toString() 11 | .trim() 12 | .split('\n') 13 | .map((line) => line.split(' ')); 14 | 15 | const scores = [10, 8, 6, 5, 4, 3, 2, 1, 0]; 16 | let redScore = 0; 17 | let blueScore = 0; 18 | 19 | results 20 | .sort((one, another) => (one[0] < another[0] ? -1 : 1)) 21 | .forEach(([, team], index) => { 22 | if (team === 'R') redScore += scores[index]; 23 | else blueScore += scores[index]; 24 | }); 25 | 26 | console.log(redScore > blueScore ? 'Red' : 'Blue'); 27 | -------------------------------------------------------------------------------- /2754.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const grade = require('fs').readFileSync(INPUT_FILE).toString().trim(); 3 | 4 | const score = { 5 | 'A+': '4.3', 6 | A0: '4.0', 7 | 'A-': '3.7', 8 | 'B+': '3.3', 9 | B0: '3.0', 10 | 'B-': '2.7', 11 | 'C+': '2.3', 12 | C0: '2.0', 13 | 'C-': '1.7', 14 | 'D+': '1.3', 15 | D0: '1.0', 16 | 'D-': '0.7', 17 | F: '0.0', 18 | }; 19 | 20 | console.log(score[grade]); 21 | -------------------------------------------------------------------------------- /27724.js: -------------------------------------------------------------------------------- 1 | /* 2 | 일단 정상적인 상황에서는 어디까지 올라갈 수 있는지를 알아야 함 3 | 그 이후를 이변으로 극복하는거임 4 | 5 | 토너먼트 방식은 최후의 승자가 무조건 강함 6 | 시은이를 위한 접대게임을 만들려면 본인보다 낮은애들을 묶어서 넣어줘야함 7 | 8 | 시은이가 6이면 12345로 접대 그룹을 만들어서 무조건 올릴 수 있는데 9 | 참가자가 2의 거듭제곱이니까 2^2 < 6 < 2^3 이라 무조건 2번 이기는 접대를 할수있음 10 | */ 11 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 12 | const [total, magic, resistance] = require('fs') 13 | .readFileSync(INPUT_FILE) 14 | .toString() 15 | .trim() 16 | .split(' ') 17 | .map(Number); 18 | 19 | const rounds = Math.floor(Math.log2(total)); 20 | const canWinCount = Math.floor(Math.log2(resistance)); 21 | const sol = Math.min(rounds, canWinCount + magic); 22 | 23 | console.log(sol); 24 | -------------------------------------------------------------------------------- /27889.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const abbreviation = require('fs').readFileSync(INPUT_FILE).toString().trim(); 3 | 4 | const getFullSchoolName = (shortName) => { 5 | switch (shortName) { 6 | case 'NLCS': return 'North London Collegiate School'; 7 | case 'BHA': return 'Branksome Hall Asia'; 8 | case 'KIS': return 'Korea International School'; 9 | case 'SJA': return 'St. Johnsbury Academy'; 10 | default: return 'Invalid name'; 11 | } 12 | }; 13 | 14 | console.log(getFullSchoolName(abbreviation)); 15 | -------------------------------------------------------------------------------- /27922.js: -------------------------------------------------------------------------------- 1 | /* 2 | 총 세 번의 정렬을 하면 되는데 3 | 각 정렬마다 '버릴 과목' 하나를 정하고 나머지 두개의 합을 기준으로 정렬 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[, listenCount], ...lectures] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | const getMaxStatus = (dropIndex) => { 14 | return lectures 15 | .map((lecture) => { 16 | return lecture.reduce((sum, value, index) => sum + (index === dropIndex ? 0 : value), 0); 17 | }) 18 | .sort((a, b) => b - a) 19 | .slice(0, listenCount) 20 | .reduce((sum, value) => sum + value, 0); 21 | }; 22 | 23 | const sol = Math.max(...Array.from({ length: 3 }, (_, idx) => getMaxStatus(idx))); 24 | 25 | console.log(sol); 26 | -------------------------------------------------------------------------------- /27962._v2.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, target] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const isVitaminString = (one, another) => { 5 | let diffCount = 0; 6 | for (let i = 0; i < one.length; i += 1) { 7 | if (one[i] !== another[i]) diffCount += 1; 8 | } 9 | return diffCount === 1; 10 | }; 11 | 12 | let sol = false; 13 | for (let length = 1; length < target.length; length += 1) { 14 | if (isVitaminString(target.slice(0, length), target.slice(-length))) { 15 | sol = true; 16 | } 17 | } 18 | 19 | console.log(sol ? 'YES' : 'NO'); 20 | -------------------------------------------------------------------------------- /27962.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, string] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n'); 4 | 5 | const countDiff = (string1, string2) => { 6 | let count = 0; 7 | 8 | for (let i = 0; i < string1.length; i += 1) { 9 | if (string1[i] !== string2[i]) count += 1; 10 | } 11 | 12 | return count; 13 | }; 14 | 15 | let isVitaminString = false; 16 | const head = []; 17 | const tail = []; 18 | 19 | for (let i = 0; i < string.length && !isVitaminString; i += 1) { 20 | head.push(string[i]); 21 | tail.push(string[string.length - 1 - i]); 22 | 23 | if (countDiff(head, [...tail].reverse()) === 1) isVitaminString = true; 24 | } 25 | 26 | console.log(isVitaminString ? 'YES' : 'NO'); 27 | -------------------------------------------------------------------------------- /27964.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const toppings = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(/\s/); 4 | 5 | const cheeseCount = [...new Set(toppings)] 6 | .filter((topping) => /Cheese$/.test(topping)) 7 | .length; 8 | 9 | console.log(cheeseCount >= 4 ? 'yummy' : 'sad'); 10 | -------------------------------------------------------------------------------- /27964_v2.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, ...toppings] = require('fs').readFileSync(INPUT_FILE).toString().trim().split(/\s/); 3 | 4 | const cheeses = toppings.filter((topping) => topping.match(/Cheese$/)); 5 | const cheeseCount = new Set(cheeses).size; 6 | 7 | console.log(cheeseCount >= 4 ? 'yummy' : 'sad'); 8 | -------------------------------------------------------------------------------- /27969.js: -------------------------------------------------------------------------------- 1 | /* 2 | 결국 근본은 괄호문제 3 | 올바른 괄호 = 8 4 | 무조건 올바르므로 여는것만 계산 5 | 숫자 = 8 6 | 문자열 = 길이+12 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const ason = require('fs').readFileSync(INPUT_FILE).toString().trim().split(' '); 10 | 11 | const sol = ason.reduce((prev, value) => { 12 | if (!Number.isNaN(Number(value))) return prev + 8; 13 | if (value === '[') return prev + 8; 14 | if (value === ']') return prev; 15 | return prev + value.length + 12; 16 | }, 0); 17 | 18 | console.log(sol); 19 | -------------------------------------------------------------------------------- /2799.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [info, ...apt] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n'); 4 | 5 | const [row, col] = info.split(' ').map(Number); 6 | 7 | const getWindowStatus = (startRow, startCol) => { 8 | for (let i = 0; i < 4; i += 1) { 9 | if (apt[startRow + i][startCol] === '.') return i; 10 | } 11 | 12 | return 4; 13 | }; 14 | 15 | const statusCounts = [0, 0, 0, 0, 0]; 16 | 17 | for (let r = 0; r < row; r += 1) { 18 | for (let c = 0; c < col; c += 1) { 19 | statusCounts[getWindowStatus(r * 5 + 1, c * 5 + 1)] += 1; 20 | } 21 | } 22 | 23 | console.log(statusCounts.join(' ')); 24 | -------------------------------------------------------------------------------- /28353.js: -------------------------------------------------------------------------------- 1 | /* 2 | 그리디 3 | 젤 무거운거+가벼운거 조합으로 최대한 무게제한 안넘게 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[, weightLimit], cats] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | cats.sort((a, b) => a - b); 14 | 15 | let sol = 0; 16 | let left = 0; 17 | let right = cats.length - 1; 18 | 19 | while (left < right) { 20 | if (cats[left] + cats[right] > weightLimit) { 21 | right -= 1; 22 | } else { 23 | left += 1; 24 | right -= 1; 25 | sol += 1; 26 | } 27 | } 28 | 29 | console.log(sol); 30 | -------------------------------------------------------------------------------- /28357.js: -------------------------------------------------------------------------------- 1 | /* 2 | 이분탐색 3 | 움직이는 값: 점수 기준치 X 4 | 비교용 값: 기준이 X점일 때 필요한 사탕 개수 5 | 기준: 최대 구매 가능한 사탕 수 K 6 | 7 | 필요한 사탕 개수가 살 수 있는 사탕 수보다 크면 점수 기준치 증가 8 | 필요한 사탕 개수가 살 수 있는 사탕 수보다 작으면 점수 기준치 감소 9 | */ 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [, maxCandy, ...scores] = require('fs') 12 | .readFileSync(INPUT_FILE) 13 | .toString() 14 | .trim() 15 | .split(/\s/) 16 | .map(Number); 17 | 18 | const countNecessaryCandies = (criteriaScore) => 19 | scores.reduce((prev, score) => prev + Math.max(0, score - criteriaScore), 0); 20 | 21 | let left = 0; 22 | let right = 1_000_000_000_000; 23 | 24 | while (left < right) { 25 | const mid = Math.floor((left + right) / 2); 26 | 27 | if (countNecessaryCandies(mid) > maxCandy) left = mid + 1; 28 | else right = mid; 29 | } 30 | 31 | console.log(left); 32 | -------------------------------------------------------------------------------- /28419.js: -------------------------------------------------------------------------------- 1 | /* 2 | 한 번의 연산으로 얻는 값 3 | 1. 홀수합+2, 짝수합+1 4 | 2. 홀수합+1, 짝수합+2 5 | 3. 홀수합+1, 짝수합+1 6 | 7 | 연산 한 번으로 홀수합과 짝수합의 차이를 1씩 줄일 수 있음 8 | 단, 수열의 길이가 3일 때는 짝수합을 증가시킬 수 없음 9 | */ 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [, ...sequence] = require('fs') 12 | .readFileSync(INPUT_FILE) 13 | .toString() 14 | .trim() 15 | .split(/\s/) 16 | .map(Number); 17 | 18 | const { oddSum, evenSum } = sequence.reduce( 19 | ({ oddSum, evenSum, isOdd }, value) => ({ 20 | oddSum: oddSum + (isOdd ? value : 0), 21 | evenSum: evenSum + (isOdd ? 0 : value), 22 | isOdd: !isOdd, 23 | }), 24 | { oddSum: 0, evenSum: 0, isOdd: true }, 25 | ); 26 | 27 | if (sequence.length === 3 && oddSum > evenSum) { 28 | console.log(-1); 29 | } else { 30 | console.log(Math.abs(oddSum - evenSum)); 31 | } 32 | -------------------------------------------------------------------------------- /28431.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const socks = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n').map(Number); 3 | 4 | let sol = -1; 5 | for (let sock = 0; sock < 10; sock += 1) { 6 | if (socks.filter((s) => s === sock).length % 2 === 1) { 7 | sol = sock; 8 | break; 9 | } 10 | } 11 | 12 | console.log(sol); 13 | -------------------------------------------------------------------------------- /28432.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const input = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const recordLength = Number(input[0]); 5 | const record = input.slice(1, 1 + recordLength); 6 | const candidates = input.slice(2 + recordLength); 7 | 8 | const questionIndex = record.findIndex((word) => word === '?'); 9 | const prevWord = record[questionIndex - 1]; 10 | const nextWord = record[questionIndex + 1]; 11 | 12 | const start = prevWord ? prevWord[prevWord.length - 1] : null; 13 | const end = nextWord ? nextWord[0] : null; 14 | 15 | const usedWords = new Set(record); 16 | 17 | const sol = candidates.find((word) => { 18 | if (usedWords.has(word)) return false; 19 | if (start && word[0] !== start) return false; 20 | if (end && word[word.length - 1] !== end) return false; 21 | return true; 22 | }); 23 | 24 | console.log(sol); 25 | -------------------------------------------------------------------------------- /28438.js: -------------------------------------------------------------------------------- 1 | /* 2 | 연산들을 행/열별로 통합한다 3 | 배열의 각 칸을 한번씩 돌면서 해당 칸에 적용된 1번/2번 연산을 계산한다 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[ROW, COL], ...operations] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | const rowOperation = new Array(ROW).fill(0); 14 | const colOperation = new Array(COL).fill(0); 15 | 16 | operations.forEach(([operator, position, value]) => { 17 | if (operator === 1) { 18 | rowOperation[position - 1] += value; 19 | } else { 20 | colOperation[position - 1] += value; 21 | } 22 | }); 23 | 24 | const sol = Array.from({ length: ROW }).map(() => new Array(COL).fill(0)); 25 | 26 | for (let r = 0; r < ROW; r += 1) { 27 | for (let c = 0; c < COL; c += 1) { 28 | sol[r][c] += rowOperation[r] + colOperation[c]; 29 | } 30 | } 31 | 32 | console.log(sol.map((row) => row.join(' ')).join('\n')); 33 | -------------------------------------------------------------------------------- /28447.js: -------------------------------------------------------------------------------- 1 | /* 2 | 재료가 10종류라 조합 가능 3 | 넣는다/안넣는다의 두 가지 경우이므로 이진법 사용 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[ingredientCount, pickCount], ...scores] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | let sol = -Infinity; 14 | 15 | for (let i = 1; i < 2 ** ingredientCount; i += 1) { 16 | const picked = [...i.toString(2).padStart(ingredientCount, '0')] 17 | .map((value, index) => [value, index]) 18 | .filter(([value]) => value === '1') 19 | .map(([, index]) => index); 20 | 21 | if (picked.length !== pickCount) continue; 22 | 23 | let taste = 0; 24 | 25 | for (let one = 0; one < picked.length; one += 1) { 26 | for (let another = one + 1; another < picked.length; another += 1) { 27 | taste += scores[picked[one]][picked[another]]; 28 | } 29 | } 30 | 31 | sol = Math.max(taste, sol); 32 | } 33 | 34 | console.log(sol); 35 | -------------------------------------------------------------------------------- /2870.js: -------------------------------------------------------------------------------- 1 | // input 2 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 3 | const [N, ...homework] = require('fs').readFileSync(INPUT_FILE).toString().trim() 4 | .split('\n'); 5 | 6 | // process 7 | const numbers = []; 8 | homework.forEach((line) => { 9 | line.split(/[a-z]+/).forEach((number) => { 10 | if (number === '') return; 11 | numbers.push(BigInt(number)); 12 | }); 13 | }); 14 | numbers.sort((a, b) => (a > b ? 1 : -1)); 15 | 16 | // output 17 | console.log(numbers.join('\n')); 18 | -------------------------------------------------------------------------------- /2908.js: -------------------------------------------------------------------------------- 1 | const reverseNumber = (number) => Number(number.toString().split('').reverse().join('')); 2 | 3 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 4 | const [A, B] = require('fs').readFileSync(INPUT_FILE).toString().trim() 5 | .split(' ') 6 | .map((number) => reverseNumber(number)); 7 | 8 | console.log(Math.max(A, B)); 9 | -------------------------------------------------------------------------------- /2914.js: -------------------------------------------------------------------------------- 1 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 2 | const [A, I] = require('fs').readFileSync(inputFile).toString().trim().split(' '); 3 | console.log(A * (I - 1) + 1); -------------------------------------------------------------------------------- /2920.js: -------------------------------------------------------------------------------- 1 | const isAscending = (sequence) => { 2 | for (let i = 1; i < 8; i += 1) { 3 | if (sequence[i] < sequence[i - 1]) return false; 4 | } 5 | return true; 6 | }; 7 | 8 | const isDescending = (sequence) => { 9 | for (let i = 1; i < 8; i += 1) { 10 | if (sequence[i] > sequence[i - 1]) return false; 11 | } 12 | return true; 13 | }; 14 | 15 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 16 | const sequence = require('fs').readFileSync(INPUT_FILE).toString().trim() 17 | .split(' ') 18 | .map(Number); 19 | 20 | let result = 'mixed'; 21 | if (isAscending(sequence)) result = 'ascending'; 22 | else if (isDescending(sequence)) result = 'descending'; 23 | 24 | console.log(result); 25 | -------------------------------------------------------------------------------- /29615.js: -------------------------------------------------------------------------------- 1 | /* 2 | 앞에서부터 M명이 전부 민규씨의 친구면 됨 3 | 임의의 두 명을 바꿀 수 있으므로 4 | 앞에서 M명 중 민규씨의 친구가 아닌사람들을 쳐내면 끝 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const [[, friendCount], waitings, friendNumbers] = require('fs') 8 | .readFileSync(INPUT_FILE) 9 | .toString() 10 | .trim() 11 | .split('\n') 12 | .map((line) => line.split(' ').map(Number)); 13 | 14 | const friendWaitingNumbers = new Set(friendNumbers); 15 | 16 | let sol = 0; 17 | for (let i = 0; i < friendCount; i += 1) { 18 | if (!friendWaitingNumbers.has(waitings[i])) sol += 1; 19 | } 20 | 21 | console.log(sol); 22 | -------------------------------------------------------------------------------- /29721.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[boardSize], ...dabbabas] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const DIRECTIONS = [ 10 | [0, 2], 11 | [0, -2], 12 | [-2, 0], 13 | [2, 0], 14 | ]; 15 | const currentPositions = new Set(dabbabas.map(([r, c]) => `${r},${c}`)); 16 | const nextPositions = new Set(); 17 | 18 | dabbabas.forEach(([r, c]) => { 19 | DIRECTIONS.forEach(([dr, dc]) => { 20 | const r2 = r + dr; 21 | const c2 = c + dc; 22 | 23 | if ( 24 | r2 < 1 || 25 | r2 > boardSize || 26 | c2 < 1 || 27 | c2 > boardSize || 28 | currentPositions.has(`${r2},${c2}`) 29 | ) { 30 | return; 31 | } 32 | 33 | nextPositions.add(`${r2},${c2}`); 34 | }); 35 | }); 36 | 37 | console.log(nextPositions.size); 38 | -------------------------------------------------------------------------------- /29730.js: -------------------------------------------------------------------------------- 1 | /* 2 | 정렬 잘하는 문제 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [, ...records] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 6 | 7 | const isBoj = (target) => { 8 | const match = target.match(/^boj.kr\/([1-9][0-9]*)$/); 9 | if (!match) return 0; 10 | return Number(match[1]); 11 | }; 12 | 13 | records.sort((one, another) => { 14 | const boj1 = isBoj(one); 15 | const boj2 = isBoj(another); 16 | 17 | if (boj1 && boj2) return boj1 - boj2; 18 | if (boj1) return 1; 19 | if (boj2) return -1; 20 | if (one.length !== another.length) return one.length - another.length; 21 | return one < another ? -1 : 1; 22 | }); 23 | 24 | console.log(records.join('\n')); 25 | -------------------------------------------------------------------------------- /29791.js: -------------------------------------------------------------------------------- 1 | /* 2 | 노바 100초 오리진 360초 3 | 각 바인드마다 면역 90초 4 | 5 | 면역이라도 스킬 시전은 되는데 바인드는 안걸림 6 | 근데 면역쿨이 짧아서 그럴일은 없음 7 | -> 스킬쿨이 돌았으면 바인드면역은 무조건 풀려있음 8 | */ 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const [, novaTimes, originTimes] = require('fs') 11 | .readFileSync(INPUT_FILE) 12 | .toString() 13 | .trim() 14 | .split('\n') 15 | .map((line) => line.split(' ').map(Number)); 16 | 17 | const nova = { 18 | use: 0, 19 | count: 0, 20 | coolDown: 100, 21 | }; 22 | const origin = { ...nova, coolDown: 360 }; 23 | 24 | const bind = (time, skill) => { 25 | if (skill.use <= time) { 26 | skill.count += 1; 27 | skill.use = time + skill.coolDown; 28 | } 29 | }; 30 | 31 | novaTimes 32 | .sort((one, another) => one - another) 33 | .forEach((time) => { 34 | bind(time, nova); 35 | }); 36 | 37 | originTimes 38 | .sort((one, another) => one - another) 39 | .forEach((time) => { 40 | bind(time, origin); 41 | }); 42 | 43 | console.log(nova.count, origin.count); 44 | -------------------------------------------------------------------------------- /30045.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const sol = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .slice(1) 8 | .filter((s) => s.includes('OI') || s.includes('01')).length; 9 | 10 | console.log(sol); 11 | -------------------------------------------------------------------------------- /3020.js: -------------------------------------------------------------------------------- 1 | /* 2 | 길이 N인 배열을 만든다 3 | 종유석 또는 석순의 시작점에 1을 찍는다 4 | 종유석 또는 석순의 (끝나는 위치-1)에 -1을 찍는다 5 | 이걸로 부분합을 구한다 6 | */ 7 | 8 | // input 9 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 10 | const [N, H, ...size] = require('fs').readFileSync(inputFile).toString().trim().split(/\s/).map(Number); 11 | 12 | // process 13 | // 종유석과 석순의 시작점과 끝점 기록 14 | const cave = new Array(H).fill(0); 15 | 16 | let flag = true; 17 | for (let s of size) 18 | { 19 | if (flag) // 석순 20 | { 21 | cave[H - s] += 1; 22 | } 23 | else // 종유석 24 | { 25 | cave[0] += 1; 26 | cave[s] += -1; 27 | } 28 | 29 | flag = !flag; 30 | } 31 | 32 | // 부분합 계산 33 | for (let i=1; i b - a); 38 | 39 | let minVal = cave[H - 1]; 40 | let cnt = 0; 41 | while (cave[cave.length - 1] === minVal) 42 | { 43 | cnt++; 44 | cave.pop(); 45 | } 46 | 47 | // output 48 | console.log(minVal, cnt); -------------------------------------------------------------------------------- /30403.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [, target] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const rainbow = 'roygbiv'; 5 | const lower = new Set(rainbow); 6 | const upper = new Set(rainbow.toUpperCase()); 7 | 8 | [...target].forEach((char) => { 9 | lower.delete(char); 10 | upper.delete(char); 11 | }); 12 | 13 | let result = 0; 14 | 15 | if (lower.size === 0) result += 1; 16 | if (upper.size === 0) result += 2; 17 | 18 | if (result === 0) { 19 | console.log('NO!'); 20 | } else if (result === 1) { 21 | console.log('yes'); 22 | } else if (result === 2) { 23 | console.log('YES'); 24 | } else { 25 | console.log('YeS'); 26 | } 27 | -------------------------------------------------------------------------------- /30404.js: -------------------------------------------------------------------------------- 1 | /* 2 | 여러 꽥꽥에 박수 한번만 치는게 유리함 3 | -> 박수는 가능한 한 늦게 쳐서 최대한 겹치게 하기 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, timeLimit, ...quacks] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split(/\s/) 11 | .map(Number); 12 | 13 | let clapCount = 0; 14 | let lastClapTime = 0; 15 | 16 | quacks.forEach((quack) => { 17 | if (quack <= lastClapTime) return; 18 | 19 | clapCount += 1; 20 | lastClapTime = quack + timeLimit; 21 | }); 22 | 23 | console.log(clapCount); 24 | -------------------------------------------------------------------------------- /30446.js: -------------------------------------------------------------------------------- 1 | /* 2 | 백트래킹 3 | 4 | 10^10 5 | 일단 Number 범위 안에는 들어감 6 | 최대 10자리라는 뜻이므로 회문수 자체는 5번정도의 재귀로 만들 수 있음 7 | 그러면 내가 해야할건 회문수가 주어진 범위 안인지 검사하는 것뿐 8 | 9 | 아 근데 0이 문제긴 하네 10 | 010 은 회문수가 아니지만 10101, 1001001 은 회문수임 11 | 10으로 나눠떨어지는 숫자는 세지 않아야 할듯함 12 | */ 13 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 14 | const max = Number(require('fs').readFileSync(INPUT_FILE).toString()); 15 | 16 | const maxDigitCount = max.toString().length; 17 | let sol = 0; 18 | const digits = Array.from('0123456789'); 19 | const traverse = (cur) => { 20 | const value = Number(cur); 21 | if (value > max || cur.length > maxDigitCount) { 22 | return; 23 | } 24 | 25 | sol += value % 10 === 0 ? 0 : 1; 26 | 27 | digits.forEach((digit) => { 28 | traverse(`${digit}${cur}${digit}`); 29 | }); 30 | }; 31 | 32 | digits.forEach((digit) => { 33 | traverse(digit); 34 | traverse(`${digit}${digit}`); 35 | }); 36 | 37 | console.log(sol); 38 | -------------------------------------------------------------------------------- /30460.js: -------------------------------------------------------------------------------- 1 | /* 2 | 누가봐도 dp 3 | 4 | opt(i, switch) := i번째 점수이고 i-2초에 스위치를 눌렀는지 여부에 따른 최댓값 5 | score(i) := i번째 얻는 점수 6 | 7 | opt(i, on) = 8 | (score(i) + score(i-1) + score(i-2)) * 2 9 | max(opt(i-3, on), opt(i-3, off)) 10 | opt(i, off) = 11 | max(opt(i-1, on), opt(i-1, off)) + score(i) 12 | */ 13 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 14 | const [, ...score] = require('fs') 15 | .readFileSync(INPUT_FILE) 16 | .toString() 17 | .trim() 18 | .split(/\s/) 19 | .map(Number); 20 | 21 | const on = []; 22 | const off = []; 23 | score.push(0, 0); 24 | 25 | for (let i = 0; i < score.length; i += 1) { 26 | off.push(Math.max(on[i - 1] ?? 0, off[i - 1] ?? 0) + score[i]); 27 | 28 | on.push( 29 | i >= 2 30 | ? (score[i] + (score[i - 1] ?? 0) + (score[i - 2] ?? 0)) * 2 + 31 | Math.max(on[i - 3] ?? 0, off[i - 3] ?? 0) 32 | : off[i], 33 | ); 34 | } 35 | 36 | console.log(Math.max(on.at(-1), off.at(-1))); 37 | -------------------------------------------------------------------------------- /30461.js: -------------------------------------------------------------------------------- 1 | /* 2 | 아 한번 낚아도 물고기가 안 없어지는구나 이러면 쉽지 3 | 4 | opt(i, j):= (i,j)에 낚싯대를 던졌을 때 낚아올릴 수 있는 물고기의 수 5 | fish(i, j):= (i,j)의 물고기 수 6 | opt(i, j) = opt(i-1, j-1) + opt(i-1, j) - opt(i-1, j-2) + fish(i, j) 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [[row, col], ...inputs] = require('fs') 10 | .readFileSync(INPUT_FILE) 11 | .toString() 12 | .trim() 13 | .split('\n') 14 | .map((line) => line.split(' ').map(Number)); 15 | 16 | const fish = inputs.slice(0, row); 17 | const opt = Array.from({ length: row }, () => Array.from({ length: col }, () => 0)); 18 | 19 | for (let r = 0; r < row; r += 1) { 20 | for (let c = 0; c < col; c += 1) { 21 | opt[r][c] = 22 | (opt[r - 1]?.[c - 1] ?? 0) + (opt[r - 1]?.[c] ?? 0) - (opt[r - 2]?.[c - 1] ?? 0) + fish[r][c]; 23 | } 24 | } 25 | 26 | const gatherings = inputs.slice(row).map(([r, c]) => opt[r - 1][c - 1]); 27 | 28 | console.log(gatherings.join('\n')); 29 | -------------------------------------------------------------------------------- /3054.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const word = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split(''); 4 | 5 | const board = Array.from(new Array(5), () => new Array(word.length * 4 + 1).fill('.')); 6 | 7 | const fillDiamond = (col, char) => { 8 | board[0][col] = char; 9 | board[1][col - 1] = char; 10 | board[1][col + 1] = char; 11 | board[2][col - 2] = char; 12 | board[2][col + 2] = char; 13 | board[3][col - 1] = char; 14 | board[3][col + 1] = char; 15 | board[4][col] = char; 16 | }; 17 | 18 | word.forEach((char, i) => { 19 | board[2][2 + 4 * i] = char; 20 | fillDiamond(2 + 4 * i, '#'); 21 | }); 22 | 23 | word.forEach((char, i) => { 24 | if (i % 3 !== 2) return; 25 | 26 | fillDiamond(2 + 4 * i, '*'); 27 | }); 28 | 29 | console.log(board.map((row) => row.join('')).join('\n')); 30 | -------------------------------------------------------------------------------- /30544.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | let [hour, minute, remainingCount] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split(/(?:\s|:)/) 7 | .map(Number); 8 | 9 | const getNextCuckoo = (hour, minute) => { 10 | if (minute < 15) return [hour, 15]; 11 | if (minute < 30) return [hour, 30]; 12 | if (minute < 45) return [hour, 45]; 13 | return [(hour % 12) + 1, 0]; 14 | }; 15 | 16 | if (minute === 0) remainingCount -= hour; 17 | else if (minute % 15 === 0) remainingCount -= 1; 18 | 19 | while (remainingCount > 0) { 20 | [hour, minute] = getNextCuckoo(hour, minute); 21 | if (minute === 0) remainingCount -= hour; 22 | else remainingCount -= 1; 23 | } 24 | 25 | console.log(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`); 26 | -------------------------------------------------------------------------------- /3060_v3.js: -------------------------------------------------------------------------------- 1 | /* 2 | 각 돼지는 매일 본인이 먹던 양만큼 좌, 우, 맞은편 돼지에게 줌 3 | -> 네 배씩 늘어남 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, ...tests] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | const getBadNewsDay = (everydayFood, firstDayFood) => { 14 | let day; 15 | let todayFood = firstDayFood; 16 | 17 | for (day = 1; todayFood <= everydayFood; day += 1) { 18 | todayFood *= 4; 19 | } 20 | 21 | return day; 22 | }; 23 | 24 | const sol = []; 25 | 26 | for (let i = 0; i < tests.length; i += 2) { 27 | const [everydayFood] = tests[i]; 28 | const firstDayFood = tests[i + 1].reduce((prev, cur) => prev + cur, 0); 29 | sol.push(getBadNewsDay(everydayFood, firstDayFood)); 30 | } 31 | 32 | console.log(sol.join('\n')); 33 | -------------------------------------------------------------------------------- /30802.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[totalCount], shirts, [shirtBundle, penBubdle]] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const shirtBundleCount = shirts.reduce((prev, cur) => prev + Math.ceil(cur / shirtBundle), 0); 10 | const penBundleCount = Math.floor(totalCount / penBubdle); 11 | const penSingleCount = totalCount % penBubdle; 12 | 13 | console.log(`${shirtBundleCount}\n${penBundleCount} ${penSingleCount}`); 14 | -------------------------------------------------------------------------------- /30803.js: -------------------------------------------------------------------------------- 1 | /* 2 | 열려있는걸 조절할 수 있나? 아마도 3 | 닫혀있는것도 조절은 할 수 있음 4 | 5 | 자스기준 아슬아슬하게 빅인트 필없을듯 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const [[tapCount], waters, , ...actions] = require('fs') 9 | .readFileSync(INPUT_FILE) 10 | .toString() 11 | .trim() 12 | .split('\n') 13 | .map((line) => line.split(' ').map(Number)); 14 | 15 | let wpm = waters.reduce((prev, cur) => prev + cur, 0); // water per minute 16 | const isOpen = new Array(tapCount).fill(true); 17 | const sol = [wpm]; 18 | 19 | actions.forEach(([action, targetInput, water]) => { 20 | const target = targetInput - 1; 21 | if (action === 1) { 22 | if (isOpen[target]) wpm += -waters[target] + water; 23 | waters[target] = water; 24 | } else if (isOpen[target]) { 25 | isOpen[target] = false; 26 | wpm -= waters[target]; 27 | } else { 28 | isOpen[target] = true; 29 | wpm += waters[target]; 30 | } 31 | 32 | sol.push(wpm); 33 | }); 34 | 35 | console.log(sol.join('\n')); 36 | -------------------------------------------------------------------------------- /30890.js: -------------------------------------------------------------------------------- 1 | /* 2 | 왼손: 오른손 개수 시간마다 한번씩 침 3 | 오른손: 왼손 개수 시간마다 한번씩 침 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | let [x, y] = require('fs').readFileSync(INPUT_FILE).toString().trim().split(' ').map(Number); 7 | 8 | const sol = []; 9 | let left = x; 10 | let right = y; 11 | let leftTime = right; 12 | let rightTime = left; 13 | 14 | while (left > 0 || right > 0) { 15 | if (leftTime === rightTime) { 16 | sol.push(3); 17 | left -= 1; 18 | right -= 1; 19 | leftTime += y; 20 | rightTime += x; 21 | } else if (leftTime < rightTime) { 22 | sol.push(1); 23 | leftTime += y; 24 | left -= 1; 25 | } else { 26 | sol.push(2); 27 | rightTime += x; 28 | right -= 1; 29 | } 30 | } 31 | 32 | console.log(sol.join('')); 33 | -------------------------------------------------------------------------------- /3107.js: -------------------------------------------------------------------------------- 1 | /* 2 | 콜론 기준으로 분리 3 | 그룹이 8개가 안되면 8개로 만듦 4 | 생략된 0 복원 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const ipv6 = require('fs').readFileSync(INPUT_FILE).toString().trim(); 8 | 9 | const groupedIPv6 = ipv6.split(':'); 10 | 11 | const omittedIndexStart = groupedIPv6.findIndex((group) => group === ''); 12 | const omittedIndexEnd = groupedIPv6[omittedIndexStart + 1] === '' ? omittedIndexStart + 2 : omittedIndexStart + 1; 13 | const omiitedGroupCount = 8 - (omittedIndexStart + (groupedIPv6.length - omittedIndexEnd)); 14 | 15 | const colonRestoredIPv6 = omittedIndexStart === -1 16 | ? groupedIPv6 17 | : [ 18 | ...groupedIPv6.slice(0, omittedIndexStart), 19 | ...new Array(omiitedGroupCount).fill('0000'), 20 | ...groupedIPv6.slice(omittedIndexEnd), 21 | ]; 22 | 23 | const zeroRestoredIPv6 = colonRestoredIPv6.map((group) => '0'.repeat(4 - group.length) + group); 24 | 25 | console.log(zeroRestoredIPv6.join(':')); 26 | -------------------------------------------------------------------------------- /31495.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const input = require('fs').readFileSync(INPUT_FILE).toString().trim(); 3 | 4 | const regex = /^"(?.+)"$/; 5 | const result = regex.exec(input); 6 | const target = result?.groups.target; 7 | 8 | console.log(target ?? 'CE'); 9 | -------------------------------------------------------------------------------- /31714.js: -------------------------------------------------------------------------------- 1 | /* 2 | 행별로 키순 정렬 3 | 열별로 가능한지 비교 4 | 5 | 본인이 행에서 제일 키가 작은데 앞줄의 키가 제일 큰 사람이랑 비교하면 안보일 확률이 높음 6 | 그냥 비슷한 애들끼리 비교하는게 나음 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [[row, col, heightDiff], ...rows] = require('fs') 10 | .readFileSync(INPUT_FILE) 11 | .toString() 12 | .trim() 13 | .split('\n') 14 | .map((line) => line.split(' ').map(Number)); 15 | 16 | const sortedRows = rows.map((row) => row.sort((a, b) => a - b)); 17 | let isSuccess = true; 18 | 19 | for (let c = 0; c < col && isSuccess; c += 1) { 20 | for (let r = 1; r < row && isSuccess; r += 1) { 21 | if (sortedRows[r][c] + heightDiff <= sortedRows[r - 1][c]) { 22 | isSuccess = false; 23 | } 24 | } 25 | } 26 | 27 | console.log(isSuccess ? 'YES' : 'NO'); 28 | -------------------------------------------------------------------------------- /31797.js: -------------------------------------------------------------------------------- 1 | /* 2 | 구현 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [[height, peopleCount], ...hands] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split('\n') 10 | .map((line) => line.split(' ').map(Number)); 11 | 12 | const positions = Array.from({ length: 10_001 }); 13 | hands.forEach(([a, b], i) => { 14 | positions[a] = i + 1; 15 | positions[b] = i + 1; 16 | }); 17 | 18 | const order = positions.filter((person) => person !== undefined); 19 | const target = (height - 1) % (peopleCount * 2); 20 | 21 | console.log(order[target]); 22 | -------------------------------------------------------------------------------- /31845.js: -------------------------------------------------------------------------------- 1 | /* 2 | 딜러 패에서 가장 비싼걸 가져오고 본인것중 가장 싼걸 주면됨 3 | 본인이 음수 점수를 얻어야 한다면 백지카드 돌리기로 0점 얻는걸로 대처 가능 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, turn, ...cards] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split(/\s/) 11 | .map(Number); 12 | 13 | cards.sort((a, b) => a - b); 14 | 15 | let left = 0; 16 | let right = cards.length - 1; 17 | let sol = 0; 18 | for (let t = 0; t < turn && left <= right; t += 1) { 19 | if (cards[right] > 0) { 20 | sol += cards[right]; 21 | left += 1; 22 | right -= 1; 23 | } 24 | } 25 | 26 | console.log(sol); 27 | -------------------------------------------------------------------------------- /3186_v2.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [info, data] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const [useThreshold, doneThreshold] = info.split(' ').map(Number); 5 | 6 | const sol = []; 7 | let isUsing = false; 8 | let notStandCount = 0; 9 | let standCount = 0; 10 | 11 | Array.from(data + '0'.repeat(doneThreshold)) 12 | .map(Number) 13 | .forEach((isStanding, index) => { 14 | if (isStanding) { 15 | notStandCount = 0; 16 | standCount += 1; 17 | } else { 18 | notStandCount += 1; 19 | standCount = 0; 20 | } 21 | 22 | if (standCount >= useThreshold) { 23 | isUsing = true; 24 | } 25 | 26 | if (isUsing && notStandCount >= doneThreshold) { 27 | isUsing = false; 28 | sol.push(index + 1); 29 | } 30 | }); 31 | 32 | console.log(sol.length ? sol.join('\n') : 'NIKAD'); 33 | -------------------------------------------------------------------------------- /31937.js: -------------------------------------------------------------------------------- 1 | /* 2 | 컴퓨터 1000대 * 로그 10000개 -> 천만 3 | 그냥 완탐 ㄱ 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [, infectedComputers, ...logs] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | infectedComputers.sort((a, b) => a - b); 14 | logs.sort((a, b) => a[0] - b[0]); 15 | 16 | const target = infectedComputers.join(' '); 17 | let sol; 18 | 19 | for (const candidate of infectedComputers) { 20 | const infected = new Set([candidate]); 21 | 22 | logs.forEach(([, start, end]) => { 23 | if (infected.has(start)) { 24 | infected.add(end); 25 | } 26 | }); 27 | 28 | const infectectedFromThisTestcase = Array.from(infected) 29 | .sort((a, b) => a - b) 30 | .join(' '); 31 | 32 | if (target === infectectedFromThisTestcase) { 33 | sol = candidate; 34 | break; 35 | } 36 | } 37 | 38 | console.log(sol); 39 | -------------------------------------------------------------------------------- /32622.js: -------------------------------------------------------------------------------- 1 | /* 2 | 같은색끼리 뭉쳐놓기 3 | 본인 바로 직전 뭉탱이 개수 + 본인 개수 = 1회 뒤집은 후 총 점수 4 | 두 번째 전 뭉탱이도 뒤집어지기 때문에 본인과 같은 색이 되지 않음 5 | */ 6 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 7 | const [, ...cards] = require('fs') 8 | .readFileSync(INPUT_FILE) 9 | .toString() 10 | .trim() 11 | .split(/\s/) 12 | .map((value) => value === '1'); 13 | 14 | const groups = []; 15 | cards.forEach((isFront, idx) => { 16 | if (cards.at(idx - 1) === isFront) { 17 | groups.push((groups.pop() ?? 0) + 1); 18 | } else { 19 | groups.push(1); 20 | } 21 | }); 22 | 23 | let max = 0; 24 | groups.forEach((group, idx) => { 25 | max = Math.max((groups[idx - 1] ?? 0) + group, max, group); 26 | }); 27 | 28 | console.log(max); 29 | -------------------------------------------------------------------------------- /32654.js: -------------------------------------------------------------------------------- 1 | /* 2 | 그래프 탐색 3 | 한번 돌릴 때마다 지목당한 사람들을 set 으로 관리 4 | 돌린 횟수가 10 이상일때 지목당한 사람들 목록에 형진이가 없으면 성공 5 | 99번까지 돌렸는데 다 형진이가 있으면 실패 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const hands = require('fs') 9 | .readFileSync(INPUT_FILE) 10 | .toString() 11 | .trim() 12 | .split('\n') 13 | .map((line) => line.split(' ').map(Number)); 14 | 15 | const solve = () => { 16 | let losers = new Set([1]); 17 | 18 | for (let i = 1; i <= 99; i += 1) { 19 | const next = new Set(); 20 | 21 | losers.forEach((person) => { 22 | hands[person].forEach((target) => { 23 | next.add(target); 24 | }); 25 | }); 26 | 27 | if (i >= 10 && !next.has(1)) { 28 | return i; 29 | } 30 | 31 | losers = next; 32 | } 33 | 34 | return -1; 35 | }; 36 | 37 | console.log(solve()); 38 | -------------------------------------------------------------------------------- /3273.js: -------------------------------------------------------------------------------- 1 | /* 2 | 집합 활용 3 | 수열 안의 각 숫자가 4 | x의 절반 미만이고 5 | (x-자기자신)이 수열에 들어있으면 조건을 만족하는 쌍 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const [, sequence, [target]] = require('fs') 9 | .readFileSync(INPUT_FILE) 10 | .toString() 11 | .trim() 12 | .split('\n') 13 | .map((line) => line.split(' ').map(Number)); 14 | 15 | const numbers = new Set(sequence); 16 | 17 | let count = 0; 18 | sequence.forEach((value) => { 19 | if (value < target / 2 && numbers.has(target - value)) { 20 | count += 1; 21 | } 22 | }); 23 | 24 | console.log(count); 25 | -------------------------------------------------------------------------------- /3372.js: -------------------------------------------------------------------------------- 1 | /* 2 | 어떤 지점을 방문하기 위해서는 위에서 오거나 왼쪽에서 와야 함 3 | 위에서 아래로, 왼쪽에서 오른쪽으로 탐색하면서 채워나가면 됨 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[size], ...board] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | const pathCounts = Array.from(new Array(size), () => new Array(size).fill(0n)); 14 | pathCounts[0][0] = 1n; 15 | 16 | for (let r = 0; r < size; r += 1) { 17 | for (let c = 0; c < size; c += 1) { 18 | const jump = board[r][c]; 19 | const pathCount = pathCounts[r][c]; 20 | 21 | if (jump && c + jump < size) pathCounts[r][c + jump] += pathCount; 22 | if (jump && r + jump < size) pathCounts[r + jump][c] += pathCount; 23 | } 24 | } 25 | 26 | console.log(pathCounts[size - 1][size - 1].toString()); 27 | -------------------------------------------------------------------------------- /3986.js: -------------------------------------------------------------------------------- 1 | /* 2 | 스택 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [, ...words] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 6 | 7 | const isGoodWord = (word) => { 8 | const stack = []; 9 | 10 | Array.from(word).forEach((char) => { 11 | if (stack.at(-1) === char) { 12 | stack.pop(); 13 | } else { 14 | stack.push(char); 15 | } 16 | }); 17 | 18 | return stack.length === 0; 19 | }; 20 | 21 | const sol = words.filter(isGoodWord).length; 22 | 23 | console.log(sol); 24 | -------------------------------------------------------------------------------- /4101.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const testCases = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map((line) => line.split(' ').map(Number)); 5 | 6 | testCases.pop(); 7 | 8 | const sol = []; 9 | testCases.forEach(([left, right]) => { sol.push(left > right ? 'Yes' : 'No'); }); 10 | 11 | console.log(sol.join('\n')); 12 | -------------------------------------------------------------------------------- /4153.js: -------------------------------------------------------------------------------- 1 | const isRightTriangle = (sides) => { 2 | sides.sort((a, b) => a - b); 3 | const [short1, short2, long] = sides; 4 | if (short1 ** 2 + short2 ** 2 === long ** 2) return true; 5 | return false; 6 | }; 7 | 8 | // input 9 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 10 | const triangles = require('fs').readFileSync(INPUT_FILE).toString().trim() 11 | .split('\n') 12 | .map((line) => line.split(' ').map(Number)); 13 | 14 | triangles.pop(); 15 | 16 | // process 17 | const sol = []; 18 | triangles.forEach((sides) => { 19 | sol.push(isRightTriangle(sides) ? 'right' : 'wrong'); 20 | }); 21 | 22 | // output 23 | console.log(sol.join('\n')); 24 | -------------------------------------------------------------------------------- /4299.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [sum, diff] = require('fs').readFileSync(INPUT_FILE).toString().trim().split(' ').map(Number); 3 | 4 | const A = (sum + diff) / 2; 5 | const B = sum - A; 6 | 7 | console.log(A >= 0 && B >= 0 && A % 1 === 0 ? `${A} ${B}` : -1); 8 | -------------------------------------------------------------------------------- /5046.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[people, budget], ...inputs] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map((line) => line.split(' ').map(Number)); 5 | 6 | const hotels = [] 7 | inputs.forEach((value, index) => { 8 | if (index % 2 === 0) hotels.push({ price: value[0] }); 9 | else hotels[hotels.length - 1].availableRooms = value; 10 | }); 11 | 12 | const availableHotels = hotels.filter( 13 | (hotel) => hotel.availableRooms.some((rooms) => (rooms >= people)), 14 | ); 15 | 16 | const price = Math.min(...availableHotels.map(({ price }) => price * people)); 17 | 18 | console.log(price <= budget ? price : 'stay home'); 19 | -------------------------------------------------------------------------------- /5073.js: -------------------------------------------------------------------------------- 1 | // input 2 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 3 | const triangle = require('fs').readFileSync(inputFile).toString().trim().split('\n'); 4 | 5 | // process 6 | const sol = []; 7 | for (let i=0; i (value * (value + 1)) / 2); 8 | 9 | console.log(sol.join('\n')); 10 | -------------------------------------------------------------------------------- /5357.js: -------------------------------------------------------------------------------- 1 | const removeRedundancy = (target) => { 2 | const result = []; 3 | for (let i = 0; i < target.length; i += 1) { 4 | if (result.at(-1) === target[i]) continue; 5 | result.push(target[i]); 6 | } 7 | return result.join(''); 8 | }; 9 | 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [, ...inputs] = require('fs') 12 | .readFileSync(INPUT_FILE) 13 | .toString() 14 | .trim() 15 | .split('\n') 16 | .map(removeRedundancy); 17 | 18 | console.log(inputs.join('\n')); 19 | -------------------------------------------------------------------------------- /5545.js: -------------------------------------------------------------------------------- 1 | /* 2 | 칼로리 높은 토핑부터 올려보면서 고점을 찾는다. 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [toppingCount, doughPrice, toppingPrice, doughCalorie, ...toppingCalories] = require('fs').readFileSync(INPUT_FILE).toString().trim() 6 | .split(/\s/) 7 | .map(Number); 8 | 9 | toppingCalories.sort((a, b) => b - a); 10 | 11 | let price = doughPrice; 12 | let calorie = doughCalorie; 13 | let bestPizza = Math.floor(doughCalorie / doughPrice); 14 | 15 | for (let i = 0; i < toppingCount; i += 1) { 16 | price += toppingPrice; 17 | calorie += toppingCalories[i]; 18 | 19 | const pizzaEfficiency = Math.floor(calorie / price); 20 | 21 | if (bestPizza < pizzaEfficiency) bestPizza = pizzaEfficiency; 22 | } 23 | 24 | console.log(bestPizza); 25 | -------------------------------------------------------------------------------- /5582.js: -------------------------------------------------------------------------------- 1 | /* 2 | 두 문자열 A, B 3 | opt(i, j) := A[i], B[j]를 포함한 최장 공통부분문자열 길이 4 | opt(i, j) = 5 | opt(i-1, j-1) + 1 (A[i-1]=B[i-1]이고 A[i]=B[i]) 6 | 1 (A[i-1]!=B[i-1]이고 A[i]=B[i]) 7 | 0 (나머지) 8 | */ 9 | 10 | // input 11 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 12 | const [A, B] = require('fs').readFileSync(inputFile).toString().trim().split('\n'); 13 | 14 | // process 15 | let opt = Array.from(new Array(A.length), () => new Array(B.length)); 16 | let sol = 0; 17 | 18 | for (let i=0; i 0 && j > 0 && A[i - 1] == B[j - 1]) 26 | val = opt[i - 1][j - 1] + 1; 27 | else 28 | val = 1; 29 | } 30 | 31 | opt[i][j] = val; 32 | sol = Math.max(sol, val); 33 | } 34 | } 35 | 36 | // output 37 | console.log(sol); -------------------------------------------------------------------------------- /5585.js: -------------------------------------------------------------------------------- 1 | const inputFile = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const changes = [500, 100, 50, 10, 5, 1]; 3 | const price = Number(require('fs').readFileSync(inputFile).toString()); 4 | 5 | const result = changes.reduce( 6 | (prev, value) => { 7 | const prevResult = prev; 8 | prevResult.count += Math.floor(prevResult.money / value); 9 | prevResult.money %= value; 10 | return prevResult; 11 | }, 12 | { money: 1000 - price, count: 0 }, 13 | ); 14 | 15 | console.log(result.count); 16 | -------------------------------------------------------------------------------- /5597.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? 'dev/stdin' : './input'; 2 | let submittedStudents = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map(Number); 5 | 6 | submittedStudents = new Set(submittedStudents); 7 | for (let student = 1; student <= 30; student += 1) { 8 | if (!submittedStudents.has(student)) console.log(student); 9 | } 10 | -------------------------------------------------------------------------------- /5928.js: -------------------------------------------------------------------------------- 1 | /* 2 | 0일 0시 0분부터 시간을 잰다 치고 시작시간이랑 끝시간 차이 구하기 3 | */ 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const [day, hour, minute] = require('fs') 6 | .readFileSync(INPUT_FILE) 7 | .toString() 8 | .trim() 9 | .split(' ') 10 | .map(Number); 11 | 12 | const toMinutes = (d, h, m) => { 13 | return d * 24 * 60 + h * 60 + m; 14 | }; 15 | 16 | const gap = toMinutes(day, hour, minute) - toMinutes(11, 11, 11); 17 | 18 | console.log(gap >= 0 ? gap : -1); 19 | -------------------------------------------------------------------------------- /6616.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const inputs = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | inputs.pop(); 5 | 6 | const encrypt = (target, jump) => { 7 | const parsed = [...target.split(' ').join('').toUpperCase()]; 8 | const result = new Array(parsed.length); 9 | 10 | let index = 0; 11 | parsed.forEach((char) => { 12 | while (result[index]) index += 1; 13 | result[index] = char; 14 | index += jump; 15 | if (index >= result.length) index = 0; 16 | }); 17 | 18 | return result.join(''); 19 | }; 20 | 21 | const sol = []; 22 | 23 | for (let i = 0; i < inputs.length; i += 2) { 24 | sol.push(encrypt(inputs[i + 1], Number(inputs[i]))); 25 | } 26 | 27 | console.log(sol.join('\n')); 28 | -------------------------------------------------------------------------------- /7891.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | const readInput = () => { 4 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 5 | const testCases = fs.readFileSync(INPUT_FILE).toString().trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | return testCases.slice(1); 9 | }; 10 | 11 | const solve = () => { 12 | const testCases = readInput(); 13 | 14 | const sol = testCases.map(([a, b]) => a + b); 15 | 16 | console.log(sol.join('\n')); 17 | }; 18 | 19 | solve(); 20 | -------------------------------------------------------------------------------- /8437.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [totalAmount, difference] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n') 4 | .map(BigInt); 5 | 6 | const natalia = (totalAmount - difference) / 2n; 7 | 8 | console.log(`${natalia + difference}\n${natalia}`); 9 | -------------------------------------------------------------------------------- /9012.js: -------------------------------------------------------------------------------- 1 | /* 2 | '('는 스택에 넣는다 3 | ')'가 나오면 스택의 '(' 하나를 뺀다 4 | 5 | 닫는 괄호가 나왔는데 스택이 비었거나 6 | 최종적으로 스택의 길이가 0이 아니면 실패 7 | */ 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [, ...inputs] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 10 | 11 | const isVps = (sentence) => { 12 | let stackLength = 0; 13 | 14 | for (let i = 0; i < sentence.length; i += 1) { 15 | if (sentence[i] === '(') { 16 | stackLength += 1; 17 | } else if (stackLength > 0) { 18 | stackLength -= 1; 19 | } else { 20 | return false; 21 | } 22 | } 23 | 24 | return stackLength === 0; 25 | }; 26 | 27 | const sol = []; 28 | 29 | inputs.forEach((input) => { 30 | sol.push(isVps(input) ? 'YES' : 'NO'); 31 | }); 32 | 33 | console.log(sol.join('\n')); 34 | -------------------------------------------------------------------------------- /9086.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [T, ...strings] = require('fs').readFileSync(INPUT_FILE).toString().trim() 3 | .split('\n'); 4 | 5 | const sol = []; 6 | strings.forEach((string) => { 7 | sol.push(`${string[0]}${string[string.length - 1]}`); 8 | }); 9 | 10 | console.log(sol.join('\n')); 11 | -------------------------------------------------------------------------------- /9498.js: -------------------------------------------------------------------------------- 1 | const inputFile = __dirname + "/input"; // "/dev/stdin"; 2 | const input = require("fs").readFileSync(inputFile).toString().trim(); 3 | const score = parseInt(input); 4 | 5 | if (score >= 90) 6 | console.log('A'); 7 | else if (score >= 80) 8 | console.log('B'); 9 | else if (score >= 70) 10 | console.log('C'); 11 | else if (score >= 60) 12 | console.log('D'); 13 | else 14 | console.log('F'); -------------------------------------------------------------------------------- /9653.js: -------------------------------------------------------------------------------- 1 | console.log(' 8888888888 888 88888\n 88 88 88 88 88 88\n 8888 88 88 88 88888\n 88 88 888888888 88 88\n88888888 88 88 88 88 888888\n\n88 88 88 888 88888 888888\n88 88 88 88 88 88 88 88\n88 8888 88 88 88 88888 8888\n 888 888 888888888 88 88 88\n 88 88 88 88 88 88888888\n'); 2 | -------------------------------------------------------------------------------- /9655.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 돌이 i개일때 상근이가 이기면 true, 지면 false 3 | 4 | opt(i-1)과 opt(i-3) 둘 중 하나라도 상근이가 지는 경우면 5 | (창영이가 마지막 돌을 가져감) 6 | opt(i)에선 상근이가 이기게 돼있음 7 | (돌이 마지막 돌+1개, 마지막+3개 있으니까 8 | 창영이가 1개 또는 3개를 가져가면 마지막 돌은 상근이가 가짐.) 9 | 10 | opt(1)=true 11 | opt(2)=false 12 | opt(3)=true 13 | opt(4)=false 14 | 15 | 홀짝으로 풀어도 되긴 함. 16 | */ 17 | 18 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 19 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 20 | 21 | let opt = [undefined, true, false, true, false]; 22 | let lastIdx = 4; 23 | 24 | while (lastIdx < N) 25 | { 26 | lastIdx++; 27 | let skWin = !(opt[lastIdx - 1] && opt[lastIdx - 3]); 28 | opt.push(skWin); 29 | } 30 | 31 | console.log(opt[N]? 'SK' : 'CY'); -------------------------------------------------------------------------------- /9655_v2.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 돌이 i개일때 상근이가 이기면 true, 지면 false 3 | 4 | opt(i-1)과 opt(i-3) 둘 중 하나라도 상근이가 지는 경우면 5 | (창영이가 마지막 돌을 가져감) 6 | opt(i)에선 상근이가 이기게 돼있음 7 | (돌이 마지막 돌+1개, 마지막+3개 있으니까 8 | 창영이가 1개 또는 3개를 가져가면 마지막 돌은 상근이가 가짐.) 9 | 10 | opt(1)=true 11 | opt(2)=false 12 | opt(3)=true 13 | opt(4)=false 14 | 15 | 홀짝으로 풀어도 되긴 함. 16 | */ 17 | 18 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 19 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 20 | 21 | let opt = new Array(1001); 22 | let lastIdx = 4; 23 | 24 | opt[1] = true; 25 | opt[3] = true; 26 | 27 | while (lastIdx < N) 28 | { 29 | lastIdx++; 30 | let skWin = !(opt[lastIdx - 1] && opt[lastIdx - 3]); 31 | opt[lastIdx] = skWin; 32 | } 33 | 34 | console.log(opt[N]? 'SK' : 'CY'); -------------------------------------------------------------------------------- /9655_v3.js: -------------------------------------------------------------------------------- 1 | /* 2 | opt(i) := 돌이 i개일때 상근이가 이기면 true, 지면 false 3 | 4 | opt(i-1)과 opt(i-3) 둘 중 하나라도 상근이가 지는 경우면 5 | (창영이가 마지막 돌을 가져감) 6 | opt(i)에선 상근이가 이기게 돼있음 7 | (돌이 마지막 돌+1개, 마지막+3개 있으니까 8 | 창영이가 1개 또는 3개를 가져가면 마지막 돌은 상근이가 가짐.) 9 | 10 | opt(1)=true 11 | opt(2)=false 12 | opt(3)=true 13 | opt(4)=false 14 | 15 | 홀짝으로 풀어도 되긴 함. 16 | */ 17 | 18 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 19 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 20 | 21 | console.log(N % 2 === 1? 'SK' : 'CY'); -------------------------------------------------------------------------------- /9658.js: -------------------------------------------------------------------------------- 1 | /* 2 | 마지막 돌을 가져가는 사람이 짐. 3 | opt(i) := 돌 i개일 때 상근이가 이기면 true, 지면 false 4 | 5 | opt(i) = 6 | opt(i-1), opt(i-3), opt(i-4) 세 경우에서 모두 상근이가 이긴다면 7 | 상근이는 opt(i)에서 무조건 짐. 8 | 왜? 돌이 i-1개, i-3개, i-4개가 되는 순간 창영이가 1개, 3개, 4개 가져가니까. 9 | 10 | opt(1) = false 11 | opt(2) = true 12 | opt(3) = false 13 | opt(4) = true 14 | */ 15 | 16 | // input 17 | const inputFile = process.platform === 'linux'? '/dev/stdin' : './input'; 18 | const N = parseInt(require('fs').readFileSync(inputFile).toString().trim()); 19 | 20 | // process 21 | let opt = [undefined, false, true, false, true]; 22 | 23 | for(let i=5; i<=N; i++) 24 | { 25 | opt.push(opt[i - 1] && opt[i - 3] && opt[i - 4]? false : true); 26 | } 27 | 28 | // output 29 | console.log(opt[N]? 'SK' : 'CY'); -------------------------------------------------------------------------------- /9782.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const data = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | data.pop(); 10 | 11 | const medians = data.map((list) => { 12 | const size = list[0]; 13 | if (size % 2 === 1) { 14 | return list[(size + 1) / 2]; 15 | } 16 | return (list[size / 2] + list[size / 2 + 1]) / 2; 17 | }); 18 | 19 | console.log(medians.map((value, index) => `Case ${index + 1}: ${value.toFixed(1)}`).join('\n')); 20 | -------------------------------------------------------------------------------- /9872.js: -------------------------------------------------------------------------------- 1 | /* 2 | '그룹'별로 숫자를 세야 함. 3 | 하지만 그룹 내에서 이름 순서가 바뀔 수 있음 4 | >> 사전순으로 정렬 5 | 정렬된 세 소의 이름을 그룹명 key로 사용 6 | */ 7 | // input 8 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 9 | const [N, ...groups] = require('fs').readFileSync(INPUT_FILE).toString().trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').sort().join(' ')); 12 | 13 | // process 14 | const count = {}; 15 | groups.forEach((group) => { 16 | if (!count[group]) count[group] = 1; 17 | else count[group] += 1; 18 | }); 19 | 20 | const sol = Object.values(count).reduce( 21 | (prev, value) => Math.max(prev, value), 22 | 0, 23 | ); 24 | 25 | // output 26 | console.log(sol); 27 | -------------------------------------------------------------------------------- /9935.js: -------------------------------------------------------------------------------- 1 | /* 2 | '모든' 폭발 문자열이 '동시에' 터져야 하는가? ㄴㄴ 3 | 어차피 서로 떨어져 있는 폭발 문자열은 서로에게 영향을 주지 않음 4 | 폭발 문자열 안에 폭발 문자열이 있는 경우 애초에 동시에 터질 수 없음 5 | 스택을 써서 폭발 문자열이 완성되는 순간 터뜨림 6 | */ 7 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 8 | const [target, bomb] = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 9 | 10 | const stack = []; 11 | 12 | Array.from(target).forEach((char) => { 13 | stack.push(char); 14 | 15 | const isBomb = stack.slice(-bomb.length).join('') === bomb; 16 | 17 | if (isBomb) { 18 | for (let i = 0; i < bomb.length; i += 1) { 19 | stack.pop(); 20 | } 21 | } 22 | }); 23 | 24 | const remainder = stack.join(''); 25 | 26 | console.log(remainder || 'FRULA'); 27 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "boj-javascript", 3 | "version": "1.0.0", 4 | "description": "my javascript solution code for baekjoon online judge", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/WaiNaat/BOJ-JavaScript.git" 12 | }, 13 | "author": "WaiNaat", 14 | "license": "MIT", 15 | "bugs": { 16 | "url": "https://github.com/WaiNaat/BOJ-JavaScript/issues" 17 | }, 18 | "homepage": "https://github.com/WaiNaat/BOJ-JavaScript#readme", 19 | "devDependencies": { 20 | "eslint": "^8.2.0", 21 | "eslint-config-airbnb-base": "^15.0.0", 22 | "eslint-config-prettier": "^8.8.0", 23 | "eslint-plugin-import": "^2.25.2", 24 | "eslint-plugin-prettier": "^5.0.0", 25 | "prettier": "^3.0.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solvedac-grand-arena-1/A.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const socks = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n').map(Number); 3 | 4 | let sol = -1; 5 | for (let sock = 0; sock < 10; sock += 1) { 6 | if (socks.filter((s) => s === sock).length % 2 === 1) { 7 | sol = sock; 8 | break; 9 | } 10 | } 11 | 12 | console.log(sol); 13 | -------------------------------------------------------------------------------- /solvedac-grand-arena-1/B.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const input = require('fs').readFileSync(INPUT_FILE).toString().trim().split('\n'); 3 | 4 | const recordLength = Number(input[0]); 5 | const record = input.slice(1, 1 + recordLength); 6 | const candidates = input.slice(2 + recordLength); 7 | 8 | const questionIndex = record.findIndex((word) => word === '?'); 9 | const prevWord = record[questionIndex - 1]; 10 | const nextWord = record[questionIndex + 1]; 11 | 12 | const start = prevWord ? prevWord[prevWord.length - 1] : null; 13 | const end = nextWord ? nextWord[0] : null; 14 | 15 | const usedWords = new Set(record); 16 | 17 | const sol = candidates.find((word) => { 18 | if (usedWords.has(word)) return false; 19 | if (start && word[0] !== start) return false; 20 | if (end && word[word.length - 1] !== end) return false; 21 | return true; 22 | }); 23 | 24 | console.log(sol); 25 | -------------------------------------------------------------------------------- /solvedac-grand-arena-1/H.js: -------------------------------------------------------------------------------- 1 | /* 2 | 연산들을 행/열별로 통합한다 3 | 배열의 각 칸을 한번씩 돌면서 해당 칸에 적용된 1번/2번 연산을 계산한다 4 | */ 5 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 6 | const [[ROW, COL], ...operations] = require('fs') 7 | .readFileSync(INPUT_FILE) 8 | .toString() 9 | .trim() 10 | .split('\n') 11 | .map((line) => line.split(' ').map(Number)); 12 | 13 | const rowOperation = new Array(ROW).fill(0); 14 | const colOperation = new Array(COL).fill(0); 15 | 16 | operations.forEach(([operator, position, value]) => { 17 | if (operator === 1) { 18 | rowOperation[position - 1] += value; 19 | } else { 20 | colOperation[position - 1] += value; 21 | } 22 | }); 23 | 24 | const sol = Array.from({ length: ROW }).map(() => new Array(COL).fill(0)); 25 | 26 | for (let r = 0; r < ROW; r += 1) { 27 | for (let c = 0; c < COL; c += 1) { 28 | sol[r][c] += rowOperation[r] + colOperation[c]; 29 | } 30 | } 31 | 32 | console.log(sol.map((row) => row.join(' ')).join('\n')); 33 | -------------------------------------------------------------------------------- /solvedac-grand-arena-3/A.js: -------------------------------------------------------------------------------- 1 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 2 | const [[totalCount], shirts, [shirtBundle, penBubdle]] = require('fs') 3 | .readFileSync(INPUT_FILE) 4 | .toString() 5 | .trim() 6 | .split('\n') 7 | .map((line) => line.split(' ').map(Number)); 8 | 9 | const shirtBundleCount = shirts.reduce((prev, cur) => prev + Math.ceil(cur / shirtBundle), 0); 10 | const penBundleCount = Math.floor(totalCount / penBubdle); 11 | const penSingleCount = totalCount % penBubdle; 12 | 13 | console.log(`${shirtBundleCount}\n${penBundleCount} ${penSingleCount}`); 14 | -------------------------------------------------------------------------------- /solvedac-grand-arena-3/E.js: -------------------------------------------------------------------------------- 1 | /* 2 | 수학을 멀리한 죄 달게 받아라 3 | 4 | 두 집합의 교집합을 두 집합의 부모로 하는 트리를 생각해보자 5 | 근데 교집합이 없을수도있잖아 6 | 일단 있다고 치면 '공통 부모'를 찾는 문제로 바뀜 7 | 8 | 나 그냥 안할래.. 9 | */ 10 | const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input'; 11 | const [, ...sets] = require('fs') 12 | .readFileSync(INPUT_FILE) 13 | .toString() 14 | .trim() 15 | .split('\n') 16 | .map((line) => new Set(line.split(' ').map(Number).slice(1))); 17 | --------------------------------------------------------------------------------