반응형

https://www.acmicpc.net/problem/14503

 

로봇 청소기와 방의 상태가 주어졌을 때, 청소하는 영역의 개수를 구하는 프로그램을 작성하시오.

로봇 청소기가 있는 방은 N X M 크기의 직사각형으로 나타낼 수 있으며, 1 X 1 크기의 정사각형 칸으로 나누어져 있다.
각각의 칸은 벽 또는 빈 칸이다. 청소기는 바라보는 방향이 있으며, 이 방향은 동, 서, 남, 북 중 하나이다. 방의 각 칸은 좌표 로 나타낼 수 있고, 가장 북쪽 줄의 가장 서쪽 칸의 좌표가 (0,0) 가장 남쪽 줄의 가장 동쪽 칸의 좌표가 (N-1, M-1)이다. 즉, 좌표 (r,c) 는 북쪽에서 (r + 1)번째에 있는 줄의 서쪽에서 (c + 1)번째 칸을 가리킨다.

처음에 빈 칸은 전부 청소되지 않은 상태이다. 로봇 청소기는 다음과 같이 작동한다.

  1. 현재 칸이 아직 청소되지 않은 경우, 현재 칸을 청소한다.
  2. 현재 칸의 주변 4칸 중 청소되지 않은 빈 칸이 없는 경우,
    1. 바라보는 방향을 유지한 채로 한 칸 후진할 수 있다면 한 칸 후진하고 1번으로 돌아간다.
    2. 바라보는 방향의 뒤쪽 칸이 벽이라 후진할 수 없다면 작동을 멈춘다.
  3. 현재 칸의 주변 4칸 중 청소되지 않은 빈 칸이 있는 경우,
    1. 반시계 방향으로 90도 회전한다.
    2. 바라보는 방향을 기준으로 앞쪽 칸이 청소되지 않은 빈 칸인 경우 한 칸 전진한다.
    3. 1번으로 돌아간다.

 

#include <iostream>
#include<memory.h>

int N, M;
int r[50][50];
int v[50][50];

//d = 0 북
//d = 1 동
//d = 2 남
//d = 3 서

int dx[4] = { 0,1,0,-1 };
int dy[4] = { -1,0,1,0 };
int count = 0;
bool DFS(int x, int y, int d)
{
    //std::cout << y << "," << x  << std::endl;
    if (v[y][x] == 0)
    {
        v[y][x] = 1;
        count++;
    }
    for (int i = 0; i < 4; ++i)
    {
        int nd = (d + 3 - i) % 4;
        int nx = x + dx[nd];
        int ny = y + dy[nd];

        if (r[ny][nx] == 0 && v[ny][nx] == 0)
        {
            v[ny][nx] = 1;
            count++;
            if (DFS(nx, ny, nd) == false)
                return false;
        }
    }
    int bd = (d + 2) % 4;
    int bx = x + dx[bd];
    int by = y + dy[bd];
    if (r[by][bx] == 0)
    {
        if (DFS(bx, by, d) == false)
            return false;
    }
    else if(r[by][bx] == 1)
        return false;
    return true;
}
int main()
{
    std::ios::ios_base::sync_with_stdio(false);
    memset(r, -1, sizeof(r));

    std::cin >> N >> M;

    int x, y, d;

    std::cin >> y >> x >> d;

    for (int i = 0; i < N; ++i)
    {
        for (int ii = 0; ii < M; ++ii)
        {
            std::cin>> r[i][ii];
        }
    }
    DFS(x, y, d);
    std::cout << count;
}

 

이동하는 모습을 디버깅해보면서 풀면 된다.

반응형
반응형

https://www.acmicpc.net/problem/15235

During the Olympiad finals we usually serve pizza for the contestants. When the food arrives, the contestants to queue to get some pizza. Each student will be given a single slice of pizza when his/her turn arrives. The problem is that some people need more than one slice of pizza to be well fed so they need to queue again for more pizza after they get the first one.
Given a list of slices needed to fed each of the contestants, compute how long it will take to fed all of them. We can give a slice of pizza every second and when a contestant is well fed he does not return to the queue.

code >>

#include <iostream>
#include<queue>
#include<vector>
int main()
{
    std::ios::ios_base::sync_with_stdio(false);
    int N = 0;
    std::cin >> N;
    std::vector<int> count(N);
    std::queue<int> q;
    for (int i= 0; i < N; ++i)
    {
        std::cin >> count[i];
        q.push(i);
    }
    std::vector<int> answer(N, 0);
    int time = 0;
    while (!q.empty())
    {
        int value = q.front();
        q.pop();
        time++;
        answer[value] = time;
        count[value]--;
        if (count[value] > 0)
        {
            q.push(value);
        }
    }
    for (int i = 0; i < N; i++)
    {
        std::cout << answer[i] << " ";
    }
    std::cout << "\n";
}

반응형

'알고리즘 > 백준' 카테고리의 다른 글

1766>문제집  (0) 2019.03.12
1654>랜선 자르기  (0) 2019.02.18
1010>다리놓기  (0) 2018.12.17
11657>타임머신  (0) 2018.12.04
1786>찾기  (0) 2018.11.26
반응형

For a = 2 and b = 7, the output should be
rangeBitCount(a, b) = 11.

Given a = 2 and b = 7 the array is: [2, 3, 4, 5, 6, 7]. Converting the numbers to binary, we get [10, 11, 100, 101, 110, 111], which contains 1 + 2 + 1 + 2 + 2 + 3 = 11 1s.

Input/Output

[execution time limit] 0.5 seconds (cpp)

[input] integer a

Guaranteed constraints:
0 ≤ a ≤ b.

[input] integer b

Guaranteed constraints:
a ≤ b ≤ 10.

 

code>>

 

int rangeBitCount(int aint b) {

    auto count = 0;

    for (int i = ai <= b; ++i)

    {

        std::bitset<4bit(i);

        count += bit.count();

    }

    return count;

}

 

반응형

'알고리즘 > codefights' 카테고리의 다른 글

18>arrayPacking  (0) 2021.04.17
17>Kill K-th Bit  (0) 2021.04.17
Challenge>formatString  (0) 2019.03.06
Challenge>fibonacciIndex  (0) 2019.03.06
16>metroCard  (0) 2019.02.24
반응형

You are given an array of up to four non-negative integers, each less than 256.

Your task is to pack these integers into one number M in the following way:

The first element of the array occupies the first 8 bits of M;
The second element occupies next 8 bits, and so on.
Return the obtained integer M.

Note: the phrase "first bits of M" refers to the least significant bits of M - the right-most bits of an integer. For further clarification see the following example.

Example

For a = [24, 85, 0], the output should be
arrayPacking(a) = 21784.

An array [24, 85, 0] looks like [00011000, 01010101, 00000000] in binary.
After packing these into one number we get 00000000 01010101 00011000 (spaces are placed for convenience), which equals to 21784.

 

code>>

 

int arrayPacking(vector<inta) {

    auto result = 0;

    for(int i=0ia.size(); ++i)

    {

        result += a[i] << i * 8;

    }

    return result;

}

 

반응형

'알고리즘 > codefights' 카테고리의 다른 글

19>rangeBitCount  (0) 2021.04.17
17>Kill K-th Bit  (0) 2021.04.17
Challenge>formatString  (0) 2019.03.06
Challenge>fibonacciIndex  (0) 2019.03.06
16>metroCard  (0) 2019.02.24
반응형

In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions. The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun, and making all the people on Earth grumpy and sad.

You figured out that some numbers have a modified single digit in their binary representation. More specifically, in the given number n the kth bit from the right was initially set to 0, but its current value might be different. It's now up to you to write a function that will change the kth bit of n back to 0.In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions. The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun, and making all the people on Earth grumpy and sad.

You figured out that some numbers have a modified single digit in their binary representation. More specifically, in the given number n the kth bit from the right was initially set to 0, but its current value might be different. It's now up to you to write a function that will change the kth bit of n back to 0.

Example

For n = 37 and k = 3, the output should be
killKthBit(n, k) = 33.

3710 = 1001012 ~> 1000012 = 3310.

For n = 37 and k = 4, the output should be
killKthBit(n, k) = 37.

The 4th bit is 0 already (looks like the Mad Coder forgot to encrypt this number), so the answer is still 37.

 

code>>

int killKthBit(int nint k) {

  return n & ~(1 << (k - 1));

}



 

반응형

'알고리즘 > codefights' 카테고리의 다른 글

19>rangeBitCount  (0) 2021.04.17
18>arrayPacking  (0) 2021.04.17
Challenge>formatString  (0) 2019.03.06
Challenge>fibonacciIndex  (0) 2019.03.06
16>metroCard  (0) 2019.02.24
반응형
Your company hired an intern database engineer, who immediately started updating the data in the system. Unfortunately, he hasn't fully grasped the concept of NULL values yet and he performed some incorrect inserts and updates to the departments table, which has the following structure:

id: the unique department ID;
name: the name of the department;
description: the description of the department.
Now you have a table where the description column holds values such as '  NULL   ', NULL, 'nil' and ' - '. You need to find out exactly how many records in the table should have NULL in the description column, regardless of whether the intern input the value correctly or not.

He used the following values to indicate NULL:

NULL: just a regular NULL value;
'NULL': NULL as a case insensitive (i.e. NuLl is also OK) string with an arbitrary number of spaces at the beginning and at the end;
'nil': nil as a case insensitive (i.e. niL is also OK) string with an arbitrary number of spaces at the beginning and at the end;
'-': a single dash with an arbitrary number of spaces at the beginning and at the end.
Given the departments table, compose the resulting table with the single column number_of_nulls containing a single value: the number of rows in the departments table that are supposed to have NULL in the description.

 

code>>

 

/*Please add ; after each select statement*/
CREATE PROCEDURE nullIntern()
BEGIN
SELECT COUNT(id) number_of_nulls FROM departments
    WHERE  description IS NULL 
    OR UPPER(TRIM(description)) = 'NULL'
    OR UPPER(TRIM(description)) = 'NIL'
    OR TRIM(description) = '-';
END

반응형

'알고리즘 > codefightsDB' 카테고리의 다른 글

24>websiteHacking  (0) 2019.03.25
23>marketReport  (0) 2019.03.25
22>soccerPlayers  (0) 2019.03.25
21>travelDiary  (0) 2019.03.25
20>movieDirectors  (0) 2019.03.25
반응형

 Implement the missing code, denoted by ellipses. You may not modify the pre-existing code.

You've been dreaming about becoming a famous hacker all your life, and now it's time to make your dreams come true! You decided to start by finding a website that has some vulnerability, and you just found a doozy. This particular website has an open database users that contains information about the people using it. What's more, it stores the queries performed on this table on the client side, which makes it super simple to hack them.


The users table contains the following columns:


id - The unique user's ID;

login - The unique user's login;

name - The user's name;

type - The user's role type (which can be "user", "admin", "moderator", etc.).

The query you have access to gathers some information about the users who have the "user" type. You don't want to get caught, so you want to carefully update it so that the query will return the records of all existing types.


Your task is to update the existing query. Note: You should add something to the query, but don't rewrite it.



code>>


CREATE PROCEDURE websiteHacking()

    SELECT id,login,name

    FROM users

    WHERE type='user'

    union select id,login,name

    from users

    where type <> 'user'

    ORDER BY id


다른 사람 코드


CREATE PROCEDURE websiteHacking()

    SELECT id,login,name

    FROM users

    WHERE type='user'

    OR 1=1

    ORDER BY id



반응형

'알고리즘 > codefightsDB' 카테고리의 다른 글

25>nullIntern  (0) 2019.04.02
23>marketReport  (0) 2019.03.25
22>soccerPlayers  (0) 2019.03.25
21>travelDiary  (0) 2019.03.25
20>movieDirectors  (0) 2019.03.25
반응형

Your company is planning to expand internationally very soon. You have been tasked with preparing a report on foreign markets and potential competitors.


After some investigation, you've created a database containing a foreignCompetitors table, which has the following structure:


competitor: the name of the competitor;

country: the country in which the competitor is operating.

In your report, you need to include the number of competitors per country and an additional row at the bottom that contains a summary: ("Total:", total_number_of_competitors)


Given the foreignCompetitors table, compose the resulting table with two columns: country and competitors. The first column should contain the country name, and the second column should contain the number of competitors in this country. The table should be sorted by the country names in ascending order. In addition, it should have an extra row at the bottom with the summary, as described above.


code>>


/*Please add ; after each select statement*/

CREATE PROCEDURE marketReport()

BEGIN


select IFNULL(country, 'Total:') as country , count(country) as competitors  from foreignCompetitors group by country WITH ROLLUP;

END

반응형

'알고리즘 > codefightsDB' 카테고리의 다른 글

25>nullIntern  (0) 2019.04.02
24>websiteHacking  (0) 2019.03.25
22>soccerPlayers  (0) 2019.03.25
21>travelDiary  (0) 2019.03.25
20>movieDirectors  (0) 2019.03.25
반응형

You have a table soccer_team that contains information about the players in your favorite soccer team. This table has the following structure:


id: the unique ID of the player;

first_name: the first name of the player;

surname: the last name of the player;

player_number: the number that the player wears (the number is guaranteed to be unique).

Create a semicolon-separated list of all the players, sorted by their numbers, and put this list in a table under a column called players. The information about each player should have the following format: first_name surname #number.


code>>


/*Please add ; after each select statement*/

CREATE PROCEDURE soccerPlayers()

BEGIN

SELECT group_concat(concat(first_name," ", surname, " #", player_number) order by player_number SEPARATOR '; ') as players from soccer_team;

END

반응형

'알고리즘 > codefightsDB' 카테고리의 다른 글

24>websiteHacking  (0) 2019.03.25
23>marketReport  (0) 2019.03.25
21>travelDiary  (0) 2019.03.25
20>movieDirectors  (0) 2019.03.25
19>usersByContinent  (0) 2019.03.25
반응형

You are an avid traveler and you've visited so many countries that when people ask you where you've been, you can't even remember all of them! Luckily, every time you travel somewhere you write down the trip information in your diary. Now you want to get a list of all the different countries that you have visited using the information in your diary.


The diary is represented as a table diary, which has the following columns:


id: the unique ID of the trip;

travel_date: the date the trip began;

country: the country to which you traveled.

Given this diary table, create a semicolon-separated list of all the distinct countries you've visited, sorted lexicographically, and put the list in a table that has a single countries column.


code>>


/*Please add ; after each select statement*/

CREATE PROCEDURE travelDiary()

BEGIN

SELECT group_concat(DISTINCT country order by country SEPARATOR ';') as countries from diary;

END

반응형

'알고리즘 > codefightsDB' 카테고리의 다른 글

23>marketReport  (0) 2019.03.25
22>soccerPlayers  (0) 2019.03.25
20>movieDirectors  (0) 2019.03.25
19>usersByContinent  (0) 2019.03.25
18>itemCounts  (0) 2019.03.13

+ Recent posts