본문으로 건너뛰기

"hackerrank" 태그로 연결된 20개 게시물개의 게시물이 있습니다.

모든 태그 보기

· 약 4분
karais89

문제 요약

안나와 브라이언이 식당에서 주문한 물건들 n 그러나 안나는 알레르기로 인해 먹는 것을 거부합니다. k개의 아이템을

수표가 오면, 그들은 그들이 공유하는 모든 항목의 비용을 나누기로 결정합니다.

그러나 브라이언은 항목을 분리하지 않고 실수로 안나에게 청구했음을 잊어 버렸을 수 있습니다.

당신은 각 아이템의 비용과 브라이언이 계산서의 일부분에 대한 안나에게 청구 한 총 금액을 받습니다.

청구서가 상당히 분할되면 Bon Appetit을 인쇄하십시오. 그렇지 않으면 브라이언이 안나에게 환불해야하는 금액을 인쇄하십시오.

첫번째 인자는 아이템의 개수이고 두번째 인자는 안나가 먹지 못하는 음식의 인덱스 값 이다.

두번째 라인의 첫번째 줄에서 첫번째 인자로 받은 인덱스는 각 음식의 값들이고.

세번째 라인은 브라이언이 안나에게 청구한 금액이다.

Sample Input 0

4 1
3 10 2 9
12

Sample Output 0

5

안나는 c[1] = 10을 먹지 못한다.

총 비용은 3+2+9=14이다. 그녀의 비용을 사람 수로 나누면 7이다.

브라이언은 그녀에게 12달러를 청구하였고, 그녀는 7달러면 내면 된다.

그러므로 우리는 안나에게 과다 청구된 금액을 출력하면 된다 12-7=5이다.

Sample Input 1

4 1
3 10 2 9
7

Sample Output 1

Bon Appetit

정확하게 안나가 청구될 금액과 일치 하므로 Bon Appetit을 출력한다.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int bonAppetit(int n, int k, int b, int[] ar) {
// Complete this function
int sum = 0;
for (int i = 0; i < n; i++)
{
if (k == i)
{
continue;
}

sum += ar[i];
}
int charge = sum / 2;
return b - charge;
}

static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] ar_temp = Console.ReadLine().Split(' ');
int[] ar = Array.ConvertAll(ar_temp,Int32.Parse);
int b = Convert.ToInt32(Console.ReadLine());
int result = bonAppetit(n, k, b, ar);
if (result == 0)
{
Console.WriteLine("Bon Appetit");
}
else
{
Console.WriteLine(result);
}
}
}

AllisonP의 답안

linq를 사용하여 풀었다.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {
static void Main(String[] args) {
int K = Console.ReadLine().Split(' ').Select(Int32.Parse).ToArray()[1];

List<int> ItemList = Console.ReadLine().Split(' ').Select(Int32.Parse).ToList();
long CorrectTotal = (ItemList.Sum(m => m) - ItemList[K]) / 2;
long AmountCharged = Convert.ToUInt32(Console.ReadLine());

if (CorrectTotal == AmountCharged)
Console.WriteLine("Bon Appetit");
else {
Console.WriteLine(AmountCharged - CorrectTotal);
}
}
}

느낀점

알고리즘 문제들을 풀다보면 c#의 경우 linq를 사용하면 쉽게 풀 수 있는 것들이 많다.

사실 linq의 사용을 의도적으로 피한 경향이 있었다.1

하지만 linq관련 문제는 여러가지 방법으로 우회 방법이 존재하며, 이제는 슬슬 적용을 할 단계인것 같습니다.


  1. 유니티의 경우 mono 2.x 버전의 버그로 정상 작동 불가.

· 약 5분
karais89

문제 요약

마린은 타임머신을 발명했으며 시간 여행을 통해 1700~2700년 사이의 프로그래머의날1 (일년중 256th)에 방문하려고 한다.

1700년에서 1917년에는 러시아에서의 공식 달력은 줄리안 달력이고, 1919년에는 그레고릭 달력 시스템이었다.

1918년에 줄리안 달력에서 그레고릭 달력으로 변경이 일어났고, 1월 31일 이후 다음날 2월 14일 변경이 됐다.

이 말은 러시아에서 1918년에는 2월 14일은 1월 32일 이었다. (중간에 14일은 간의 기간은 달력 변경으로 삭제)

두 가지 달력 시스템에서 2 월은 가변 일수가있는 유일한 달입니다.

윤년 기간에는 29 일, 그 외 모든 연도에는 28 일이 있습니다

줄리아 달력에서 윤년은 4로 나눌 수 있습니다. 그레고리력에서 윤년은 다음 중 하나입니다.

  • 400으로 나눌수 있다.
  • 4로 나누어지지만 100으로는 나누어지지 않는다.

1년을 감안할 때 그 해의 공식 러시아 달력에 따라 해당 연도의 날짜를 찾으십시오.

그런 다음 dd.mm.yyyy 형식으로 인쇄하십시오. 여기서 dd는 두 자리 날이고 mm은 두 자리 월이며 yyyy는 y입니다.

Sample Input 0

2017

Sample Output 0

13.09.2017

2017년은 1월은 31일, 2월은 28일, 3월은 31일, 4월은 30일 ,5월은 31일, 6월은 30일, 7월은 31일, 8월은 31일이다. 31+28+31+30+31+30+31+30+31+31 = 243이다. 프로그래머의 날은 256번째 날이므로. 256-243=13이다. 그러므로 9월 13일이 프로그래머의 날이다.

Sample Input 0

2016

Sample Output 0

12.09.2017

위와 같은 방식이지만 2016년은 2월이 29일인 윤년이다. 그러므로 31+29+31+30+31+30+31+30+31+31 = 244이고 256-244=12이다. 그러므로 9월 12일이 프로그래머의 날이다.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int[] GetDays(int year) {
int[] days = new int[12] {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

bool isJulianCalendar = year <= 1917;
bool isGregorianCalendar = year >= 1919;

if (isJulianCalendar)
{
if (year % 4 == 0)
{
days[1] = 29;
}
}
else if (isGregorianCalendar)
{
if ((year % 4 == 0 && year % 100 != 0) ||
(year % 400 == 0))
{
days[1] = 29;
}
}
else
{
// julianCalendar & isGregorianCalendar
// January 31 after -> February 14
days[1] = 28 - 14 + 1;
}

return days;
}

static string solve(int year){
// Complete this function
int[] days = GetDays(year);
int programmerDay = 256;
int y = year;
int m = 0;
int d = 0;
for (int i = 0; i < days.Length; i++)
{
programmerDay -= days[i];
if (programmerDay < 0)
{
m = i + 1;
d = programmerDay + days[i];
break;
}
}

return String.Format("{0:00}.{1:00}.{2:0000}", d, m, y);
}

static void Main(String[] args) {
int year = Convert.ToInt32(Console.ReadLine());
string result = solve(year);
Console.WriteLine(result);
}
}

mfv의 답안

#pragma GCC diagnostic ignored "-Wunused-result"

#include <cstdio>
#include <cassert>

int main() {
int y;
scanf("%d", &y);
int daysInFebruary;
if (y == 1918) {
daysInFebruary = 28 - 13;
} else if (y < 1918) {
if (y % 4 == 0) {
daysInFebruary = 29;
} else {
daysInFebruary = 28;
}
} else {
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
daysInFebruary = 29;
} else {
daysInFebruary = 28;
}
}
int day = 256 - 31 - daysInFebruary - 31 - 30 - 31 - 30 - 31 - 31;
assert(1 <= day && day <= 30);
printf("%02d.%02d.%04d", day, 9, y);
return 0;
}

느낀점

문제 자체가 더 어려운 느낌.

문제를 풀려면 그레고릭 달력 줄리안 달력 개념과 윤년 계산 법 등을 알고 있어야 한다.

문제를 풀면서 프로그래머의 날이 있다는 사실 도 알았다..

문제 자체는 출제자와 거의 똑같은 방식으로 푼 것 같다.


  1. 0x100일째의 날을 기념한다고 하는 날. 10진 수로 변경하면 매 해의 256번째 날.

· 약 3분
karais89

문제 요약

n 마리의 새 무리가 대륙을 날고 있습니다.

각 새는 유형이 있으며, 다른 유형은 ID 번호 1,2,3,4,5로 지정됩니다.

새 무리에서 가장 일반적으로 많이 보유하고 있는 무리의 유형을 출력하고, 만약 유형의 개수가 같으면, 유형의 개수의 숫자가 작은 것을 출력하세요.

Sample Input

6
1 4 4 4 5 3

Sample Output 0

4

설명

  • Type 1: 1 bird
  • Type 2: 0 birds
  • Type 3: 1 bird
  • Type 4: 3 birds
  • Type 5: 1 bird

가장 높은 빈도에서 발생하는 유형 번호는 4 유형이므로 응답으로 4를 인쇄합니다.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int migratoryBirds(int n, int[] ar) {
// Complete this function
int[] typeCount = new int[5];
for (int i = 0; i < n; i++)
{
typeCount[ar[i]-1]++;
}

int maxIndex = 0;
int max = typeCount[0];
for (int i = 1; i < typeCount.Length; i++)
{
if (typeCount[i] > max)
{
maxIndex = i;
max = typeCount[i];
}
}
return maxIndex+1;
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] ar_temp = Console.ReadLine().Split(' ');
int[] ar = Array.ConvertAll(ar_temp,Int32.Parse);
int result = migratoryBirds(n, ar);
Console.WriteLine(result);
}
}

StefanK의 답안

import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] types = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
types[arr_i] = in.nextInt();
}
int[] frequencies = new int[6]; //A
for (int i = 0; i < types.length; i++) { //B
frequencies[types[i]] += 1; //C
}
int mostCommon = 0;
for (int i = 1; i < frequencies.length; i++) { //D
if (frequencies[mostCommon] < frequencies[i]) {
mostCommon = i; //E
}
}
System.out.println(mostCommon);
}
}

느낀점

배열을 생성하고 그 배열에 타입을 저장하면 끝나는 문제

내가 푼 방식에서 굳이 max 값을 저장할 필요가 없다는걸 봤다.

어차피 maxIndex 값을 가지고 있기 때문에 그 값으로 비교를 하면 된다.

· 약 2분
karais89

문제 요약

당신에게는 n개의 일차원 배열이 주어진다.

여기서 k는 (i,j)의 쌍을 나누는 수이다. (단 i < j) k로 나누었을때 나머지가 없는 쌍의 개수를 구해라.

Sample Input

6 3
1 3 2 6 1 2

Sample Output 0

5

설명

  • (0,2) -> 1+2=3
  • (0,5) -> 1+2=3
  • (1,3) -> 3+6=9
  • (2,4) -> 2+1=3
  • (4,5) -> 1+2=3

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int divisibleSumPairs(int n, int k, int[] ar) {
// Complete this function
int totalCount = 0;
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if ((ar[i]+ar[j])%k==0)
{
totalCount++;
}
}
}
return totalCount;
}

static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] ar_temp = Console.ReadLine().Split(' ');
int[] ar = Array.ConvertAll(ar_temp,Int32.Parse);
int result = divisibleSumPairs(n, k, ar);
Console.WriteLine(result);
}
}

wanbo의 답안

#include <bits/stdc++.h>
using namespace std;

int n, k;
int a[N];

int main() {
cin >> n >> k;
for(int i = 0; i < n; i++) cin >> a[i];

int res = 0;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if((a[i] + a[j]) % k == 0) res++;
cout << res << endl;
return 0;
}

usinha02

문제를 풀면서 혹시 O(n)으로 푸는 방법이 존재하지 않을까 싶었는데, 역시나 존재한다.

using namespace std;
int main(){

int n;
int k;
cin >> n >> k;
int a[n];
int m[k];
for(int i=0; i<k; i++) {
m[i]=0;
}

for(int i = 0; i < n; i++) {
cin >> a[i];
m[a[i]%k]++;
}

int sum=0;
sum+=(m[0]*(m[0]-1))/2;
for(int i=1; i<=k/2 && i!=k-i; i++) {
sum+=m[i]*m[k-i];
}

if(k%2==0) {
sum+=(m[k/2]*(m[k/2]-1))/2;
}

cout<<sum;
return 0;
}

느낀점

그냥 간단하게 이중 for문을 사용하여 구할 수 있다.

· 약 6분
karais89

문제 요약

Sample Input

2 3
2 4
16 32 96

Sample Output

3
a = {2,4}

b = {16, 32, 96}

x = 4:
a의 모든 요소는 4로 나누어짐
b의 모든 요소는 4로 나누어짐

x = 8:
a의 모든 요소는 8로 나누어짐
b의 모든 요소는 8로 나누어짐

x = 16:
a의 모든 요소는 16로 나누어짐
b의 모든 요소는 16로 나누어짐

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int GetTotalX(int[] a, int[] b)
{
// Complete this function
int lcm = GetLCMByArr(a);
int gcd = GetGCDByArr(b);


int totalCount = 0;
for (int i = lcm, j=2; i <= gcd; i=lcm*j, j++)
{
if (gcd % i == 0)
{
totalCount++;
}
}
return totalCount;
}

// GCD = greatest common divisor
static int GetGCD(int a, int b)
{
int gcd = 1;
int minVal = Math.Min(a, b);
for (int i = 2; i <= minVal; i++)
{
if (a % i == 0 && b % i == 0)
{
gcd = i;
}
}
return gcd;
}

// LCM = least common multiple
static int GetLCM(int a, int b)
{
return a * b / GetGCD(a, b);
/*
int lcm = 1;
int maxVal = Math.Max(a, b);
for (int i = maxVal; ;i++)
{
if (i % a == 0 && i % b == 0)
{
lcm = i;
break;
}
}
return lcm;
*/
}

static int GetGCDByArr(int[] arr)
{
int gcd = arr[0];
for (int i = 1; i < arr.Length; i++)
{
gcd = GetGCD(gcd, arr[i]);
}
return gcd;
}

static int GetLCMByArr(int[] arr)
{
int lcm = arr[0];
for (int i = 1; i < arr.Length; i++)
{
lcm = GetLCM(lcm, arr[i]);
}
return lcm;
}

static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int m = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
string[] b_temp = Console.ReadLine().Split(' ');
int[] b = Array.ConvertAll(b_temp,Int32.Parse);
int total = GetTotalX(a, b);
Console.WriteLine(total);
}
}

zemen의 답안

import java.util.*;

public class Solution {
public static int gcd(int a, int b) {
while (a > 0 && b > 0) {

if (a >= b) {
a = a % b;
}
else {
b = b % a;
}
}

return a + b;
}

public static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}

public static int getTotalX(int[] a, int[] b) {

int multiple = 0;
for(int i : b) {
multiple = gcd(multiple, i);
}
// System.err.println("Multiple: " + multiple);

int factor = 1;
for(int i : a) {
factor = lcm(factor, i);
if (factor > multiple) {
return 0;
}
}

if (multiple % factor != 0) {
return 0;
}
// System.err.println("Factor: " + factor);

int value = multiple / factor;

int max = Math.max(factor, value);
int totalX = 1;

for (int i = factor; i < multiple; i++) {
if (multiple % i == 0 && i % factor == 0) {
totalX++;
}
}
return totalX;
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scan.nextInt();
}
int[] b = new int[m];
for (int i = 0; i < m; i++) {
b[i] = scan.nextInt();
}
scan.close();

int total = getTotalX(a, b);
System.out.println(total);
}
}

t_tashasin의 답안

알고리즘 수행 속도 O(n log(n))의 해결방안:

  1. a 배열의 LCM(최소공배수)을 찾아라.
  2. b 배열의 GCD(최대공약수)를 찾아라.
  3. GCD를 균등하게 나누는 LCM의 배수를 세어라.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
int[] b = new int[m];
for(int b_i=0; b_i < m; b_i++){
b[b_i] = in.nextInt();
}

int f = lcm(a);
int l = gcd(b);
int count = 0;
for(int i = f, j =2; i<=l; i=f*j,j++){
if(l%i==0){ count++;}
}
System.out.println(count);
}

private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}

private static int gcd(int[] input) {
int result = input[0];
for (int i = 1; i < input.length; i++) {
result = gcd(result, input[i]);
}
return result;
}

private static int lcm(int a, int b) {
return a * (b / gcd(a, b));
}

private static int lcm(int[] input) {
int result = input[0];
for (int i = 1; i < input.length; i++) {
result = lcm(result, input[i]);
}
return result;
}

느낀점

먼저 처음에 문제 자체를 이해를 잘 못해서 해맨 상태에서, 최대 공약수 및 최소 공배수를 이용해서 문제를 푸는 것 자체는 파악을 했다.

하지만 다양한 테스트 케이스에서 통과를 하지 못하고, 결국 문제 자체는 힌트를 보고 풀었다.

결국엔 최대 공약수 및 최소 공배수의 알고리즘을 알면 풀 수 있는 문제라고 생각해서 문제를 풀었지만, 테스트 케이스에서 인자가 조금 많아지니, 알고리즘 자체의 성능이 문제가 되어 테스트 케이스에 통과하지 못했다.

최종적으로는 유클리드 호제법을 사용하여 문제를 풀어야 된다.

유클리드 호제법에 대해서는 나중에 한번 다시 한번 정리를 해봐야 될 것 같다.

· 약 4분
karais89

문제 요약

릴리는 초콜렛 n 줄을 가지고 있다.

론의 생일이라 릴리는 자신의 초콜릿 바를 일부분 줄려고 한다.

생일의 월은 m일은 d라고 했을시 m에 연속된 숫자의 합이 d와 일치하는 숫자의 카운터 만큼 줄려고 한다.

Sample Input 0

5
1 2 1 3 2
3 2

Sample Output 0

2

2번 연속해서 나오는 수의 합이 3인 숫자.

1+2=3, 2+1=3 이므로 2개이다.

Sample Input 1

6
1 1 1 1 1 1
3 2

Sample Output 1

0

2번 연속해서 나온 숫자의 합이 6인 것은 없다.

Sample Input 2

1
4
4 1

Sample Output 2

1

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int solve(int n, int[] s, int d, int m){
// Complete this function
int count = 0;
for (int i = 0; i < n; i++)
{
int sum = 0;

for (int j = i; j < i + m && j < n; j++)
{
sum += s[j];
}

if (sum == d)
{
count++;
}
}
return count;
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] s_temp = Console.ReadLine().Split(' ');
int[] s = Array.ConvertAll(s_temp,Int32.Parse);
string[] tokens_d = Console.ReadLine().Split(' ');
int d = Convert.ToInt32(tokens_d[0]);
int m = Convert.ToInt32(tokens_d[1]);
int result = solve(n, s, d, m);
Console.WriteLine(result);
}
}

adititayal9의 답안

import java.util.*;

public class Solution {

public static int getNumberOfWays(int n, int d, int m, int[] sum) {
// Modify array to make each 'i' contain the running sum of prior elements
for (int i = 1; i < n; i++) {
sum[i] += sum[i - 1];
}

// Set number of ways counter
// If there are >= 'm' squares AND the first possible piece has sum = 'd', 1
// Else, 0
int numberOfWays = (m <= n && sum[m - 1] == d) ? 1 : 0;

// Check the sums for pieces ending at index 'm' through 'n - 1'
for (int i = m; i < n; i++) {
// If the sum of the piece is equal to 'd'
if (sum[i] - sum[i - m] == d) {
// Increment ways counter
numberOfWays++;
}
}

return numberOfWays;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] squares = new int[n];
for(int squares_i=0; squares_i < n; squares_i++){
squares[squares_i] = in.nextInt();
}
int d = in.nextInt();
int m = in.nextInt();
in.close();

System.out.println(getNumberOfWays(n, d, m, squares));
}
}

Prince_sai의 답안

int getWays(int n, int* squares, int d, int m){
// Complete this function
int sum[105];
int count=0;
sum[0]=0;
for(int i=0;i<n;i++)sum[i+1]=sum[i]+squares[i];
for(int i=0;i<=n-m;i++){
if(sum[i+m]-sum[i]==d){
count++;
}
}
return count;
}

kcoddington0925의 답안

역시 linq를 사용하면 단 세줄로 문제를 풀 수 있다..

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{

static int getWays(int[] squares, int d, int m)
{
int ways = 0;
for (int i = 0; i < squares.Length - (m - 1); i++)
if (squares.Skip(i).Take(m).Sum() == d) ways++;
return ways;
}

static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] s_temp = Console.ReadLine().Split(' ');
int[] s = Array.ConvertAll(s_temp, Int32.Parse);
string[] tokens_d = Console.ReadLine().Split(' ');
int d = Convert.ToInt32(tokens_d[0]);
int m = Convert.ToInt32(tokens_d[1]);
int result = getWays(s, d, m);
Console.WriteLine(result);
}
}

느낀점

문제 자체를 이해하면 쉽게 풀 수 있는 문제이다.

사실 코딩을 하다 보면, for문 안에 여러개의 조건문을 넣는 경우가 그렇게 많지는 않았던 것 같은데..

일단 내가 짠 코드의 경우 O(n2) 이고 출제자의 경우는 O(n) 인듯 하다.

출제자는 그냥 배열을 이전 합계의 누적 합계가 포함되도록 배열을 수정하고, 거기서 답을 찾는 방식으로 진행 한 것 같다.

· 약 3분
karais89

문제 요약

마리아는 농구를 시즌에 n 게임을 치른다.

마리아는 프로로 뛰고 싶기 때문에, 그녀의 경기가 끝날때 마다 점수를 배열로 순차적으로 매깁니다.

그녀는 시즌 별로 최고 점수를 깬 횟수와 최저 점수를 깬 횟수를 기록 합니다.

첫번째 인자로는 시즌의 총 경기 횟수를 입력 받고, 나머지 인자로는 그 시즌의 점수를 입력 받습니다.

Sample Input 0

9
10 5 20 20 4 5 2 25 1

Sample Output 0

2 4

설명.

그녀는 인덱스 2(20점), 7(25점)에서 최고 점수 기록을 깨고, 인덱스 1(5점), 4(4점), 6(2점), 8(1점) 에서 최저 점수 기록을 깻습니다.

Sample Input 0

10
3 4 21 36 10 28 35 5 24 42

Sample Output 0

4 0

그녀는 최고 기록을 4번이나 세웠고, 시즌에서 첫번째 기록에 비교해서 최악의 점수를 깬 적은 없습니다.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int[] getRecord(int[] s){
// Complete this function
int score = s[0];
int bestScore = s[0];
int worstScore = s[0];

int bestCount = 0;
int worstCount = 0;

for (int i = 1; i < s.Length; i++)
{
if (s[i] > bestScore)
{
bestCount++;
bestScore = s[i];
}

if (s[i] < worstScore)
{
worstCount++;
worstScore = s[i];
}
}

return new int[] {bestCount, worstCount};
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] s_temp = Console.ReadLine().Split(' ');
int[] s = Array.ConvertAll(s_temp,Int32.Parse);
int[] result = getRecord(s);
Console.WriteLine(String.Join(" ", result));
}
}

StefanK의 답안

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] score = new int[n];
for(int score_i=0; score_i < n; score_i++){
score[score_i] = in.nextInt();
}
int best = 0;
int worst = 0;
int bestCounter = 0;
int worstCounter = 0;
best = score[0];
worst = score[0];
for (int i = 1; i < score.length; i++) {
if (score[i] < worst) {
worst = score[i];
worstCounter++;
}
if (score[i] > best) {
best = score[i];
bestCounter++;
}
}
System.out.println(bestCounter + " " + worstCounter);
}
}

느낀점

확인 해보니 답안과 똑같은 방식으로 풀음.

설명 자체를 하기 곤란한 난이도의 문제 였던 것 같다.

· 약 5분
karais89

문제 요약

두 마리의 캥거루가 있다.

  • 첫 번째 캥거루의 위치는 x1 이고, 캥거루는 v1 만큼 점프해서 이동한다.
  • 두 번째 캥거루의 위치는 X2 이고, 캥커루는 V2 만큼 점프해서 이동한다.

그들이 같은 시간에 같은 장소에 착률 할 수 있으면 YES를 출력하세요.

인풋의 순서는 각각 x1, v1, x2, v2 이다.

Sample Input 0

0 3 4 2

Sample Output 0

YES
  1. 0 -> 3 -> 6 -> 9 -> 12
  2. 4 -> 6 -> 8 -> 10 -> 12

이 캥거리는 4번 점프하면 같은 장소에 만난다.

Sample Input 1

0 2 5 3

Sample Output 1

NO

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static string kangaroo(int x1, int v1, int x2, int v2) {
// first check impossible case : Position is in front and speed is faster
if ((x1 > x2 && v1 > v2) || (x2 > x1 && v2 > v1))
{
return "NO";
}

// backPos and frontPos check
int backPos = 0;
int frontPos = 0;
int backVel = 0;
int frontVel = 0;
if (x1 > x2)
{
backPos = x2;
frontPos = x1;
backVel = v2;
frontVel = v1;
}
else
{
backPos = x1;
frontPos = x2;
backVel = v1;
frontVel = v2;
}

// loop jumping
while (true)
{
backPos += backVel;
frontPos += frontVel;

if (backPos == frontPos)
return "YES";
else if (backPos > frontPos)
return "NO";
}
}

static void Main(String[] args) {
string[] tokens_x1 = Console.ReadLine().Split(' ');
int x1 = Convert.ToInt32(tokens_x1[0]);
int v1 = Convert.ToInt32(tokens_x1[1]);
int x2 = Convert.ToInt32(tokens_x1[2]);
int v2 = Convert.ToInt32(tokens_x1[3]);
string result = kangaroo(x1, v1, x2, v2);
Console.WriteLine(result);
}
}

wanbo의 답안

python으로 문제를 풀었다.

다음 방정식에 해가 존재하는지만 파악 하면된다.

x1 + t v1 == x2 + t v2

이것은 아래와도 같다.

(x2-x1)%(v1-v2) == 0

x1, v1, x2, v2 = map(int, raw_input().split())
X = [x1, v1]
Y = [x2, v2]
back = min(X, Y)
fwd = max(X, Y)
dist = fwd[0] - back[0]

while back[0] < fwd[0]:
back[0] += back[1]
fwd[0] += fwd[1]
if fwd[0] - back[0] >= dist:
break

print ["NO", "YES"][back[0] == fwd[0]]
}

nasimoyz의 (x2-x1)%(v1-v2) == 0에 대한 설명

Input이 0 3 4 2 일때

k1 --- k2
x=0 x=4
v=3 v=2

k1이 도약할때 4에 오는지 확인해야 된다.

v1이 4의 요소인지 여부에 대한 간단한 문제입니다 (명확하게 넘어갈 것입니다).

(x2 - x1) % v1 = (4-0) % 3 = 1

k2가 움직이는 또 다른 경우를 상상해 봅시다 : v2 = 2

v1> v2 인 경우 v1이 결국 따라 잡을 것입니다.

각 점프에서 K1이 3 단계를 진행하고 K2가 2 단계를 진행하면 K1은 각 점프에서 K2를 얻습니다 (각 점프는 점프보다 1 덜 떨어집니다).

이제 K1은 원래 거리 (4)에 가까워집니다.

4 6 8 10 12  <- K2
0 3 6 9 12 <- K1
4 3 2 1 0 <- Difference
1 1 1 1 <- Rate

거리가 닫히는 비율이 그들 사이의 원래 거리까지 합칠 수 있다면 (4), 결국 만나게 될 것입니다.

이제 만나지 않는 예를 들어 보겠습니다. 3 4 10 2

10 12 14 16 18  <- K2
3 7 11 15 19 <- K1
7 5 3 1 -1 <- Difference
2 2 2 2 <- Rate

속도는 원래 거리의 요인이 아니므로 결코 만날 수 없습니다.. 7 % 2 = 1

느낀점

일단 푸는 방식 자체는 비슷한 것 같다.

C# 에서 제공해주는 Min과 Max 함수를 사용했으면 좀더 코드량은 줄어들었을것 같다.

· 약 4분
karais89

문제 요약

Input 설명

  1. 첫 번째 라인에는 s,t (s와 t는 샘의 집의 범위)
  2. 두 번째 라인에는 a,b (a는 사과위치, b는 오렌지위치)
  3. 세 번째 라인에는 m,n (m은 사과개수, n은 오렌지개수)
  4. 각 사과가 점 a에서 떨어지는 각각의 거리를 나타내는 공백으로 구분 된 정수
  5. 각 오렌지가 점 b에서 떨어지는 각각의 거리를 나타내는 공백으로 구분 된 정수

Output 설명

  1. 샘 집에서 떨어지는 사과 수를 인쇄
  2. 샘 집에서 덜어지는 오렌지 수를 인쇄

샘의 집 주위에 떨어지는 사과와 오렌지 개수를 구하는 문제

Sample Input

7 11
5 15
3 2
-2 2 1
5 -6

Sample Output

1
1
  • 첫번째 사과 위치 : 5-2=3
  • 두번째 사과 위치 : 5+2=7
  • 세번째 사과 위치 : 5+1=6
  • 첫번재 오렌지 위치 : 15+5=20
  • 두번째 오렌지 위치 : 15-6=9
  • 샘의 집 위치는 7~11이고 그 사이에 존재하는 사과 개수는 1개, 오렌지 개수는 1 개이다.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static void Main(String[] args) {
string[] tokens_s = Console.ReadLine().Split(' ');
int s = Convert.ToInt32(tokens_s[0]);
int t = Convert.ToInt32(tokens_s[1]);
string[] tokens_a = Console.ReadLine().Split(' ');
int a = Convert.ToInt32(tokens_a[0]);
int b = Convert.ToInt32(tokens_a[1]);
string[] tokens_m = Console.ReadLine().Split(' ');
int m = Convert.ToInt32(tokens_m[0]);
int n = Convert.ToInt32(tokens_m[1]);
string[] apple_temp = Console.ReadLine().Split(' ');
int[] apple = Array.ConvertAll(apple_temp,Int32.Parse);
string[] orange_temp = Console.ReadLine().Split(' ');
int[] orange = Array.ConvertAll(orange_temp,Int32.Parse);

int appleSum = 0;
int orangeSum = 0;

for (int i = 0; i < m; i++)
{
int aPos = apple[i] + a;
if (aPos >= s && aPos <= t)
{
appleSum++;
}
}

for (int i = 0; i < n; i++)
{
int oPos = orange[i] + b;
if (oPos >= s && oPos <= t)
{
orangeSum++;
}
}

Console.Write("{0}\n{1}", appleSum, orangeSum);
}
}

vatsalchanana의 답안

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
int s, t, a, b, n, m, d, ans1=0, ans2=0;
cin >> s >> t >> a >> b >> m >> n;

for(int i=0;i<m; i++) {
cin>>d;
d = a+d;
if(d>=s && d<=t)
ans1++;
}
for(int i=0;i<n; i++) {
cin>>d;
d = b+d;
if(d>=s && d<=t)
ans2++;
}
cout << ans1 << endl;
cout << ans2 << endl;
return 0;
}

느낀점

특정 범위 안에 수를 구하는 문제. if문과 && 연산자만 사용하면 풀 수 있는 문제이다. 문제 자체는 어려운게 없다.

문제 자체에 대한 설명이 문제의 난이도에 비해서 좀 길지 않나 싶다.

· 약 3분
karais89

문제 요약

  • 모든 학생들은 0에서 100까지의 등급을 받는다.
  • 40 미만의 점수는 실패한 등급이다.

샘은 대학 교수이며 아래와 같이 등급을 매긴다.

  • 등급간의 차이는 5씩 차이가 나며 등급과 3미만의 차이가 나면 다음 등급으로 반올림 한다.
  • 만약 38 미만등급이면 결과가 실패한 등급이므로 반올림 하지 않는다.
  • 예를들어 84점이면 85로 반올림 되고 29점이면 29이다.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int[] solve(int[] grades){
// Complete this function
int[] finalGrades = new int[grades.Length];
for (int i = 0; i < grades.Length; i++)
{
// less than 38 fail grade
if (grades[i] < 38)
{
finalGrades[i] = grades[i];
}
else
{
int firstValue = grades[i] / 10 * 10;
int secondValue = grades[i] % 10;
int roundedValue = 0;
if (secondValue > 5)
{
roundedValue = firstValue + 10;
}
else
{
roundedValue = firstValue + 5;
}

if (roundedValue - grades[i] < 3)
{
finalGrades[i] = roundedValue;
}
else
{
finalGrades[i] = grades[i];
}
}
}
return finalGrades;
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
int[] grades = new int[n];
for(int grades_i = 0; grades_i < n; grades_i++){
grades[grades_i] = Convert.ToInt32(Console.ReadLine());
}
int[] result = solve(grades);
Console.WriteLine(String.Join("\n", result));


}
}

nabila_ahmed의 답안

#include <bits/stdc++.h>
using namespace std;

void solution() {
int n, x;
cin>>n;
for(int i=0; i<n; i++){
cin>>x;
if(x>=38 and x%5>=3){
while(x%5!=0){
x++;
}
}
cout<<x<<endl;
}
}

int main () {
solution();
return 0;
}

enilaydagdemir의 답안

static int solve(int grade){
int result = grade;
if (grade >= 38)
{
if ((5 - (grade % 5) + grade) - grade < 3)
result = 5 - (grade % 5) + grade;
}
return result;
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
int[] grades = new int[n];
for(int grades_i = 0; grades_i < n; grades_i++){
grades[grades_i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(solve(grades[grades_i]));
}
}

느낀점

내가 생각한거랑은 좀 다른 해결책을 제시함.

내 생각은

  1. fianlValue 값을 구한다.
  2. finalValue 에서 현재 값을 뺀다.
  3. 그 수의 차이가 3미만이면 finalValue 값 (반올림 한다)
  4. 그 수의 차이가 3이상이면 원래 값 (반올림 하지 않는다)

이런식으로 문제를 해결했다.

등급이 점수 5를 기준으로 나누어 지므로.

(5 - (grade % 5) + grade) 이런식으로도 다음 등급을 파악할 수 있다.

ex) 71

5 - (1) + 71 = 75

ex) 89

5 - (4) + 89 = 90