////////////////////////////////////////////////
// Globals
enum class AccountType
{
    Saving = 0
};

// AccountType을 string으로 변환하는 함수
const char* toString(AccountType type) noexcept
{
    if (type == AccountType::Saving)
        return "Saving";

    return "NULL";
}

////////////////////////////////////////////////
// Classes

class BankAccount
{
public:

    BankAccount(uint32_t balance, const string& accNum, const string& bankName, AccountType accountType)
        :balance(balance), accNum(accNum), bankName(bankName), accountType(accountType) { }

    // 입금
    bool Deposit(uint32_t money)
    {
        const uint32_t before = balance;
        balance += money;

        writeStatement(before, money, balance, statementOption::DEPOSIT);
        return true;
    }

    // 출금
    bool WithDrawal(uint32_t money)
    {
        if (balance < money)
            return false;

        const uint32_t before = balance;
        balance -= money;

        writeStatement(before, money, balance, statementOption::WITHDRAWAL);
        return true;
    }

    // 계좌 정보 출력
    void Print()
    {
        cout << "Account: " << accNum
            << " | Bank: " << bankName
            << " | Type: " << toString(accountType) << endl;

        for (auto d : statement)
        {
            cout << d << endl;
        }
    }

private:

    enum statementOption
    {
        DEPOSIT,
        WITHDRAWAL
    };

    // 계좌 내역 저장
    void writeStatement(uint32_t before, uint32_t money, uint32_t after, statementOption option)
    {
        string t = "Balance: $" + std::to_string(before) + " -> ";

        if (option == statementOption::DEPOSIT)
            t += "Deposit $" + std::to_string(money) + " -> ";

        if (option == statementOption::WITHDRAWAL)
            t += "Withdrawal $" + std::to_string(money) + " -> ";

        t += "Balance: $" + std::to_string(after);
        statement.push_back(t);
    }

private:

    uint32_t balance;
    string accNum;
    string bankName;
    AccountType accountType;
    vector<string> statement; // 거래 내역 저장
};

// Class: Customer
class Customer
{
public:

    Customer(const string& name, const string& phoneNum, const string& address, size_t age)
        :name(name), phoneNum(phoneNum), address(address), age(age), acc(nullptr) {
    }

    ~Customer()
    {
        if (acc != nullptr)
            delete acc;
    }

    // 계좌 생성
    bool AddAccount(uint32_t balance, string accNum, string bankName, AccountType accountType)
    {
        if (acc != nullptr)
            return false;

        acc = new BankAccount(balance, accNum, bankName, accountType);
        return true;
    }

    // 입금
    bool Deposit(uint32_t money)
    {
        if (acc == nullptr)
            return false;

        return acc->Deposit(money);
    }

    // 출금
    bool WithDrawal(uint32_t money)
    {
        if (acc == nullptr)
            return false;

        return acc->WithDrawal(money);
    }

    // 고객 정보 출력
    void PrintCustomer()
    {
        cout << "Customer: " << name
            << " | Phone: " << phoneNum
            << " | Age: " << age << endl;
    }

    // 고객 계좌 정보 출력
    void PrintAccount()
    {
        if (acc == nullptr)
            cout << "No Account" << endl;
        else
            acc->Print();
    }

private:

    string name;
    string phoneNum;
    string address;
    size_t age;
    BankAccount* acc;
};

////////////////////////////////////////////////
// Main
int main()
{
    Customer alice = { "Alice", "010-1234-5678", "Korea", 27 };
    alice.AddAccount(1500, "123-456", "Hana", AccountType::Saving);
    alice.Deposit(200);
    alice.WithDrawal(500);
    alice.PrintCustomer();
    alice.PrintAccount();

    return 0;
}

 

초기 코드

더보기
char name[] = "2103546";

int tree[7][7] = {
    /*2*/0,1,1,1,0,0,0,
    /*1*/0,0,0,0,1,0,0,
    /*0*/0,0,0,0,0,1,1,
    /*3*/0,0,0,0,0,0,0,
    /*5*/0,0,0,0,0,0,0,
    /*4*/0,0,0,0,0,0,0,
    /*6*/0,0,0,0,0,0,0
};
int len = 7;

int main()
{
    // 1. Values
    string boss = "";
    string under = "";
    int target = 2;

    // 2. Solve
    for (int i = 0; i < len; ++i)
    {
        for (int j = 0; j < len; ++j)
        {
            if (tree[i][target] == 1)
                boss = name[i];

            if (i == target && tree[target][j] == 1)
                under += name[j] + string(" ");
        }
    }

    // 3. Output
    cout << "boss:" << boss << endl;
    cout << "under:" << under;

    return 0;
}

개선 코드

///////////////////////////////////////////////
// Globals

int tree[7][7] = {
    0,0,0,0,1,0,1,
    0,0,0,0,0,1,0,
    1,1,0,1,0,0,0,
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,0
};
int totalNodes = 7;

int boss = 0;
vector<int>child;

///////////////////////////////////////////////
// Functions

void FindNode()
{
    for (int i = 0; i < totalNodes; ++i)
    {
        // Find parent
        if (tree[i][0] == 1)
            boss = i;

        // Find Child
        if (tree[0][i] == 1)
            child.push_back(i);
    }
}

///////////////////////////////////////////////
// Main

int main()
{
    /* Solve */
    FindNode();

    /* Print */
    cout << "boss:" << boss << endl << "under:";
    for (auto d : child)
    {
        cout << d << " ";
    }

    return 0;
}

 


초기 코드

더보기
#pragma once
#include <iostream>
#include <string>
#include <vector>

using namespace std;

///////////////////////////////////////////////
// Globals

// DAT[i] : 트리의 Level i 에 속한 노드의 인덱스들이 저장되어 있는 vector<char>
vector<char> DAT[8];
char name[] = "ABHCDGEF";

char target;
int targetIdx;
int targetLevel;

int NodeCnt = 8;
int tree[8][8] = {
    /*A*/0,1,1,1,0,0,0,0,
    /*B*/0,0,0,0,0,0,0,0,
    /*H*/0,0,0,0,0,0,0,0,
    /*C*/0,0,0,0,1,1,1,0,
    /*D*/0,0,0,0,0,0,0,1,
    /*G*/0,0,0,0,0,0,0,0,
    /*E*/0,0,0,0,0,0,0,0,
    /*F*/0,0,0,0,0,0,0,0
};

///////////////////////////////////////////////
// Functions

// lev에 해당하는 노드의 자식들을 저장하는 함수
void SaveUnder(int lev)
{
    // lev의 모든 노드 확인
    vector<char>& nodes = DAT[lev];
    for (auto d : nodes)
    {
        // Find target level
        if (d == targetIdx)
            targetLevel = lev;

        for (int j = 0; j < NodeCnt; ++j)
        {
            // 트리배열에서 각 노드의 자식을 찾아 다음 레벨에 저장
            if (tree[d][j] == 1)
            {
                DAT[lev + 1].push_back(j);
            }
        }
    }
}

int main()
{
    /*1. Input value*/
    cin >> target;
    targetIdx = strchr(name, target) - name;


    /*2. Solve*/
    // Put root node
    DAT[0].push_back(0);

    // Run function 'Solve' until DAT is empty
    int i = 0;
    while (DAT[i].empty() == false)
    {
        SaveUnder(i);
        ++i;
    }

    /*3. Print*/
    if (DAT[targetLevel].size() == 1)
    {
        cout << "없음";
    }
    else
    {
        for (auto d : DAT[targetLevel])
        {
            // Don't print 'target'
            if (name[d] == target) continue;
            cout << name[d] << " ";
        }
    }

    return 0;
}

개선 코드

///////////////////////////////////////////////
// Globals

char target;
int targetIdx;
int targetLevel;

const int totalNodes = 8;
int tree[totalNodes][totalNodes] = {
    /*A*/0,1,1,1,0,0,0,0,
    /*B*/0,0,0,0,0,0,0,0,
    /*H*/0,0,0,0,0,0,0,0,
    /*C*/0,0,0,0,1,1,1,0,
    /*D*/0,0,0,0,0,0,0,1,
    /*G*/0,0,0,0,0,0,0,0,
    /*E*/0,0,0,0,0,0,0,0,
    /*F*/0,0,0,0,0,0,0,0
};
char name[] = "ABHCDGEF";

// DAT[i] = i번째 노드의 레벨
char DAT[totalNodes] = { 0 };

///////////////////////////////////////////////
// Functions

void DFS(int idx, int lev)
{
    // Base case:
    if (totalNodes <= idx)
        return;

    // Recursive step:
    for (int i = 0; i < totalNodes; ++i)
    {
        if (tree[idx][i] == 0) continue;

        // Put level of 
        // DAT[i] = child node of the current node
        DAT[i] = lev + 1;
        DFS(i, lev + 1);
    }
}

///////////////////////////////////////////////
// Main

int main()
{
    /*1. Update value*/
    cin >> target;
    targetIdx = strchr(name, target) - name;


    /*2. Solve*/
    // Fill in DAT
    DFS(0, 0);

    // Insert into the string the nodes at the same level as the target level.
    string ret = "";
    int targetLev = DAT[targetIdx];
    for (int i = 0; i < totalNodes; ++i)
    {
        if (DAT[i] == targetLev && name[i] != target)
            ret += name[i];
    }


    /*3. Print*/
    cout << (ret.length() == 0 ? "없음" : ret);
    return 0;
}

 


///////////////////////////////////////////////
// Globals

char tree[] = " ADFZCGQH";

///////////////////////////////////////////////
// Main

int main()
{
    // 1. Input value
    char a, b;
    cin >> a >> b;

    // 2. Find index 'a, b'
    int idxA, idxB;
    for (int i = 0; i < sizeof(tree); ++i)
    {
        if (tree[i] == a)
            idxA = i;
        if (tree[i] == b)
            idxB = i;
    }

    // 3. Compare each index
    bool ret = false;
    if (idxA / 2 == idxB || idxB / 2 == idxA)
        ret = true;

    // 4. Print
    cout << (ret ? "부모자식관계" : "아님");

    return 0;
}

 


///////////////////////////////////////////////
// Globals

string name = "0234561";
int tree[7][7] = {
    /*0*/0,1,1,1,0,0,0,
    /*2*/0,0,0,0,1,1,0,
    /*3*/0,0,0,0,0,0,1,
    /*4*/0,0,0,0,0,0,0,
    /*5*/0,0,0,0,0,0,0,
    /*6*/0,0,0,0,0,0,0,
    /*7*/0,0,0,0,0,0,0,
};
const int totalNodes = 7;

///////////////////////////////////////////////
// Functions

// Print sub node corresponding to idx in tree
void TraverseLevelOrder(int idx)
{
    // Base case: Stop if is out of bounds
    if (totalNodes <= idx)
        return;
    
    // work step: Print current Node
    cout << name[idx] << " ";

    // Recursive step : Traverse all sub nodes of the current node
    for (int i = 0; i < totalNodes; ++i)
    {
        if (tree[idx][i] != 1) continue;

        TraverseLevelOrder(i);
    }

    return;
}

///////////////////////////////////////////////
// Main

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

 


///////////////////////////////////////////////
// Globals

const int totalNodes = 8;
int tree[totalNodes] = { 0,3,4,2,4,1,0,3 };

///////////////////////////////////////////////
// Functions

void DFS(int idx)
{
    // Base case: 
    if (totalNodes <= idx || tree[idx] == 0)
        return;

    // Work step:
    cout << tree[idx] << " ";

    // Recursive step:
    DFS(idx * 2);
    DFS(idx * 2 + 1);

    return;
}

///////////////////////////////////////////////
// Main

int main()
{
    // Update value
    int idx, val;
    cin >> idx >> val;
    tree[idx] = val;

    // Do tree traversal
    DFS(1);

    return 0;
}

 


///////////////////////////////////////////////
// Globals

const int totalNodes = 9;
int tree[totalNodes][totalNodes] = {
    0,1,1,0,0,0,0,0,0,
    0,0,0,1,1,1,0,0,0,
    0,0,0,0,0,0,1,1,1,
    0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,
};

string path = { 0 };

///////////////////////////////////////////////
// Functions

void DFS(int idx)
{
    // Base case: 
    if (path.length() == 3)
    {
        cout << path << endl;
        return;
    }

    // Recursive step:
    for (int i = 0; i < totalNodes; ++i)
    {
        if (tree[idx][i] != 1) continue;

        path.push_back('0' + i);
        DFS(i);
        path.pop_back();
    }

    return;
}

///////////////////////////////////////////////
// Main

int main()
{
    // Do tree traversal
    path[0] = '0';
    DFS(0);

    return 0;
}

 


///////////////////////////////////////////////
// Globals

const int totalNodes = 8;
int tree[totalNodes] = { 0,3,7,10,5,6,3,6 };
int path[totalNodes] = { 0 };
int pushIdx = 0;

///////////////////////////////////////////////
// Functions

void DFS(int idx)
{
    // Base case: 
    if (totalNodes <= idx)
        return;

    // Work step:
    path[pushIdx++] = tree[idx];
    if (tree[idx] % 2 == 0)
    {
        // Print path
        for (int i = 0; i < pushIdx; ++i)
        {
            cout << path[i] << " ";
        }
        cout << endl;
    }

    // Recursive step:
    DFS(idx * 2);
    DFS(idx * 2 + 1);

    path[--pushIdx] = 0;
    return;
}

///////////////////////////////////////////////
// Main

int main()
{
    DFS(1);

    return 0;
}

 

'코딩 테스트 > 알고리즘 풀이' 카테고리의 다른 글

[LV17] 연습 문제  (0) 2025.06.07
[LV16] 복습 문제  (0) 2025.06.02
[LV15] 연습 문제  (0) 2025.05.24
[설계편] 코테 준비 문제  (0) 2025.05.24
[LV14] 연습 문제  (0) 2025.05.21

class Queue
{
public:
	struct Node
	{
		int data;
		Node* next;
	};

	Queue() = default;

	void Push(int d)
	{
		Node* temp = new Node();
		temp->data = d;
		temp->next = nullptr;

		if (size == 0)
			head = temp;
		else
			tail->next = temp;

		tail = temp;
		++size;
	}

	bool Pop()
	{
		if (size == 0)
			return false;

		Node* temp = head->next;
		delete[] head;
		head = temp;
		--size;
		return true;
	}

	void Print()
	{
		Node* temp = head;
		while (temp != nullptr)
		{
			cout << temp->data << " ";
			temp = temp->next;
		}
	}

private:
	Node* head = nullptr;
	Node* tail = nullptr;
	size_t size = 0;
};

int main()
{
	int input;
	cin >> input;

	Queue q;
	for (int i = 0; i < input; ++i)
	{
		char c; cin >> c;
		int in; cin >> in;
		if (c == 'E')
		{
			q.Push(in);
		}
		if (c == 'D')
		{
			if (q.Pop() == false)
			{
				cout << "Error";
				return 0;
			}
		}
	}

	q.Print();

	return 0;
}

 


struct ABC
{
	ABC(int a, int b, int c, int d, int x)
		:x(x)
	{
		data[0] = a;
		data[1] = b;
		data[2] = c;
		data[3] = d;
	}

	void Print()
	{
		for (auto d : data)
		{
			cout << d << " ";
		}
		cout << endl; cout << x << endl;
	}

	int data[4] = { 0 };
	int x = 0;
};

int main()
{
	ABC a = ABC(1, 2, 3, 4, 10);
	ABC b = ABC(7, 8, 9, 10, 15);

	ABC* p, * g;
	p = &a;
	g = &b;

	p->Print();
	g->Print();


	return 0;
};

 


char DAT[300] = { 0 };
int main()
{
	string s;
	cin >> s;

	int cnt = 0;
	for (auto d : s)
	{
		if (++(DAT[d]) == 1)
			++cnt;
	}

	cout << cnt << "종류";
	return 0;
};

 


using pii = pair<int, int>;

// (y, x)
pii dc [2] = {
	{0,1}, //우측
	{1,0} //하단
};

char board[4][4] = {
	1,0,0,0,
	0,1,0,0,
	0,0,0,1,
	0,1,0,0
};

int main()
{
	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			for (int k = 0; k < 2; ++k)
			{
				int ty = i + dc[k].first;
				int tx = j + dc[k].second;

				//정상 좌표 확인
				if (4 <= ty || 4 <= tx) continue;

				if (board[i][j] == 1 && board[ty][tx])
				{
					cout << "위험한 상태";
					return 0;
				}

			}
			
		}
	}
	cout << "안전한 상태";
	return 0;
};

 


using pii = pair<int, int>;

char input[4][10] = { 0 };

int main()
{
	// (val ,idx)
	pii max = pii(-1, -1);
	pii min = pii(INT_MAX, -1);

	for (int i = 0; i < 4; ++i)
	{
		cin >> input[i];
		int len = strlen(input[i]);
		if (max.first < len)
		{
			max.first = len;
			max.second = i;
		}
		if (len < min.first)
		{
			min.first = len;
			min.second = i;
		}
	}

	char* pMax = input[max.second];
	char* pMin = input[min.second];

	while (*pMax != 0)
	{
		*pMax = tolower(*pMax);
		pMax++;
	}
	while (*pMin != 0)
	{
		*pMin = tolower(*pMin);
		pMin++;
	}

	for (int i = 0; i < 4; ++i)
	{
		cout << input[i] << endl;
	}

	return 0;
};

 


int input[3][4] = {
	0,0,0,0,
	1,0,0,0,
	1,0,0,0
};

int main()
{
	for (int i = 0; i < 4; ++i)
	{
		cin >> input[0][i];
	}

	for (int i = 1; i < 3; ++i)
	{
		for (int j = 1; j < 4; ++j)
		{
			input[i][j] = input[i - 0][j - 1] + input[i - 1][j - 0];
		}
	}

	for (int i = 0; i < 3; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			cout << input[i][j] << " ";
		}
		cout << endl;
	}

	return 0;
};

 


struct coord
{
	coord(int x = 0, int y = 0)
		:x(x), y(y) {	};
	int x;
	int y;
};
using pic = pair<int, coord>;

// 오름차순
bool cmp(pic& a, pic& b)
{
	return a.first > b.first;
}

int main()
{
	vector<pic> v;
	for (int i = 0; i < 3; ++i)
	{
		for (int j = 0; j < 3; ++j)
		{
			int t; cin >> t;
			v.push_back(make_pair(t, coord(i, j)));
		}
	}

	sort(v.begin(), v.end(), cmp);

	cout << "첫번째:" << v[0].first << "(" << v[0].second.x << "," << v[0].second.y << ")" << endl;
	cout << "두번째:" << v[1].first << "(" << v[1].second.x << "," << v[1].second.y << ")" << endl;
	return 0;
};

 


char board[4][4] = { 0 };

// (y, x)
using pii = pair<int, int>;
pii DAT[8] = {
	{-1,0}, // 상
	{-1,1}, // 우상
	{0,1}, // 우
	{1,1}, // 우하
	{1,0}, // 하
	{1,-1}, // 좌하
	{0,-1}, // 좌
	{-1,-1}, // 좌상
};

int main()
{
	for (int i = 0; i < 3; ++i)
	{
		int x, y;
		cin >> y >> x;
		board[y][x] = '#';
	}

	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			char& c = board[i][j];
			if (c != '#') continue;
			
			for (int k = 0; k < 8; ++k)
			{
				int dy = i + DAT[k].first;
				int dx = j + DAT[k].second;

				// 유효한 좌표인지 확인
				if (dy < 0 || 4 <= dy || dx < 0 || 4 <= dx) continue;
				// #인지 확인
				if (board[dy][dx] == '#') continue;

				board[dy][dx] = '@';
			}
		}
	}

	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			if (board[i][j] == 0)
				cout << "_";
			else 
				cout << board[i][j];
		}
		cout << endl;
	}

	return 0;
};

 


char graph[4][4] = {
	0,1,1,1,
	0,0,1,0,
	0,0,0,0,
	0,0,1,0
};

int main()
{
	int ret[4] = { 0 };
	int max = -1;
	int maxIdx = -1;
	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			ret[j] += graph[i][j];

			if (max < (++ret[j]))
			{
				max = ret[j];
				maxIdx = j;
			}
		}
	}

	cout << char('A' + maxIdx);

	return 0;
};

 


 

// Struct ////////////////
struct pii
{
	pii(int y = 0, int x = 0)
		:y(y), x(x) {
	};

	int y;
	int x;
};


// Globals ///////////////
pii input;
vector<pii> pos[10];
int board[4][4] = { 0 };

// (y, x)
pii DAT[4] = {
	{-1,0}, // 상
	{0,1}, // 우
	{1,0}, // 하
	{0,-1}, // 좌
};


// Function //////////////
// num을 찾아 사방에 num + 1을 대입
int cnt = 1;
void Func(int num)
{

	// 해당 레벨의 모든 좌표 탐색
	for (auto d : pos[num])
	{
		// 사방 확인
		for (int i = 0; i < 4; ++i)
		{
			int ty = d.y + DAT[i].y;
			int tx = d.x + DAT[i].x;

			// 유효 하지 않으면 continue
			if (ty < 0 || 4 <= ty || tx < 0 || 4 <= tx) continue;
			// 이미 숫자가 들어있으면 continue
			if (board[ty][tx] != 0) continue;

			// 사방에 다음 숫자 삽입 후 좌표 저장
			board[ty][tx] = num + 1;
			pos[num + 1].push_back(pii(ty, tx));
			++cnt;
		}
	}
}

int main()
{
	cin >> input.y >> input.x;
	board[input.y][input.x] = 1;
	pos[1].push_back(pii(input.y, input.x));

	
	int lev = 1;
	while (cnt < 16)
	{
		Func(lev++);
	}
	
	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			cout << board[i][j] << " ";
		}
		cout << endl;
	}

	return 0;
};

 


string name[5]
{
	"Amy",
	"Bob",
	"Chole",
	"Diane",
	"Edger"
};

int input[5][5] = {
	/*A*/0,0,0,0,1,
	/*B*/1,0,0,0,0,
	/*C*/0,1,0,0,0,
	/*D*/0,1,0,0,0,
	/*E*/0,0,0,0,0,
};

int main()
{
	int max = -1;
	int maxIdx = -1;

	int DAT[5] = { 0 };
	for (int i = 0; i < 5; ++i)
	{
		for (int j = 0; j < 5; ++j)
		{
			if (input[i][j] == 1)
				++DAT[j];

			if (max < DAT[j])
			{
				max = DAT[j];
				maxIdx = j;
			}
		}
	}

	cout << name[maxIdx];

	return 0;
};

 


int input[5][5] = {
	/*A*/0,1,7,2,0,
	/*B*/1,0,8,0,5,
	/*C*/7,8,0,3,6,
	/*D*/2,0,3,0,0,
	/*E*/0,5,6,0,0
};

int main()
{
	for (int i = 0; i < 5; ++i)
	{
		for (int j = 0; j < 5; ++j)
		{
			if (i == j || input[i][j] == 0) continue;
			cout << (char)('A' + i) << " " << (char)('A' + j) << " " << input[i][j] << endl;
		}
	}

	return 0;
};

 


class List
{
public:

	struct Node
	{
		char data;
		Node* next;
	};

	void add(int val)
	{
		Node* buff = new Node();
		buff->data = val;
		buff->next = nullptr;

		if (size == 0)
		{
			head = buff;
		}
		if (0 < size)
		{
			tail->next = buff;
		}
		tail = buff;

		++size;
	}

	void Print()
	{
		Node* temp = head;
		while (temp != nullptr)
		{
			cout << temp->data << " ";
			temp = temp->next;
		}
	}

private:

	Node* head = nullptr;
	Node* tail = nullptr;
	size_t size = 0;

};


int main()
{
	int a;
	cin >> a;

	List l;
	for (int i = 0; i < a; ++i)
	{
		char c;
		cin >> c;
		l.add(c);
	}

	l.Print();
	return 0;
};

 


class List
{
public:

	struct Node
	{
		int data[4] = { 0 };
		Node* next = nullptr;

		Node() = default;
		Node(int a, int b, int c, int d)
			:data{ a,b,c,d }, next(nullptr) {}

		Node(const Node& n)
			:data{ n.data[0],n.data[1],n.data[2],n.data[3] }, next(nullptr) {}
	};

	void Push(int a, int b, int c, int d)
	{
		Node* buff = new Node(a, b, c, d);
		
		if (size == 0)
		{
			head = buff;
		}
		if (0 < size)
		{
			tail->next = buff;
		}

		tail = buff;
		++size;
	}

	friend std::istream& operator>>(std::istream& in, List& l)
	{
		int a, b, c, d;
		in >> a >> b >> c >> d;
		l.Push(a, b, c, d);
		return in;
	}

	void Check()
	{
		Node* temp = head;
		Node* tempPre = head;

		while (temp != nullptr)
		{
			// 배열이 모두 1일때 temp를 지운다.
			if (temp->data[0] == 1 && temp->data[1] == 1 &&
				temp->data[2] == 1 && temp->data[3] == 1)
			{
				if (tempPre == temp)
				{
					temp = temp->next;
					*tempPre = Node(0, 0, 0, 0);
					tempPre->next = temp;
				}
				else
				{
					tempPre->next = temp->next;
					delete temp;
					temp = tempPre->next;

					// 지웠으면 앞에 리스트 추가
					Node* buff = new Node(0, 0, 0, 0);
					buff->next = head;
					head = buff;
				}
			}
			else
			{
				tempPre = temp;
				temp = temp->next;
			}
		}
	}

	void Print()
	{
		Node* temp = head;
		while (temp != nullptr)
		{
			for (auto d: temp->data)
			{
				cout << d << " ";
			}
			cout << endl;
			temp = temp->next;
		}
		cout << endl << endl;
	}

private:

	Node* head = nullptr;
	Node* tail = nullptr;
	size_t size = 0;
};


int main()
{
	List l;
	
	for (int i = 0; i < 5; ++i)
	{
		cin >> l;
	}

	l.Check();
	l.Print();

	return 0;
};

'코딩 테스트 > 알고리즘 풀이' 카테고리의 다른 글

[LV16] 복습 문제  (0) 2025.06.02
[LV16] 연습 문제  (0) 2025.05.27
[설계편] 코테 준비 문제  (0) 2025.05.24
[LV14] 연습 문제  (0) 2025.05.21
[String편] 코테 준비 문제  (0) 2025.05.18

int num[] = { 1,2,3 };
int size = sizeof(num) / sizeof(int);

class Solution
{
public:

	Solution(int* d)
	{
		mSize = size;
		memcpy(data, d, sizeof(int) * mSize);
		memcpy(origin, d, sizeof(int) * mSize);
	}

	int* shuffle()
	{
		// Fishers Yates Shuffle
		for (int i = mSize - 1; 0 < i; --i)
		{
			int t = rand() % i;
			std::swap(data[i], data[t]);
		}

		return data;
	}

	int* reset()
	{
		memcpy(data, origin, sizeof(int) * 3);
		return data;
	}

private:
	int data[3];
	int origin[3];
	int mSize;
};

 


class Stack
{
public:

    struct node
    {
        node() = default;
        node(int d, int m)
        {
            data = d;
            min = m;
        }

        int data;
        int min;
    };

    Stack() = default;

    void push(int val)
    {
        if (topIdx < 0)
            nodes[topIdx + 1] = node(val, val);
        else
            nodes[topIdx + 1] = node(val, nodes[topIdx].min < val ? nodes[topIdx].min : val);
        ++topIdx;
    }

    void pop() {
        --topIdx;
    }

    int top() {
        return nodes[topIdx].data;
    }

    int getMin() {
        return nodes[topIdx].min;
    }

private:

    node nodes[30'000];
    int size = 0;
    int topIdx = -1;
};

'코딩 테스트 > 알고리즘 풀이' 카테고리의 다른 글

[LV16] 연습 문제  (0) 2025.05.27
[LV15] 연습 문제  (0) 2025.05.24
[LV14] 연습 문제  (0) 2025.05.21
[String편] 코테 준비 문제  (0) 2025.05.18
[LV10] 연습 문제  (0) 2025.05.12

class list
{
public:
    struct Node
    {
        int value = 0;
        Node* next = nullptr;
    };

    void Push(int data)
    {
        Node* buff = new Node;
        
        if (mSize == 0)
            mHead = buff;
        if (0 < mSize)
            mTop->next = buff;
            
        buff->value = data;
        buff->next = nullptr;
        mTop = buff;
        mSize++;
    }

    void Print()
    {
        Node* t = mHead;
        do
        {
            cout << t->value <<" ";
            t = t->next;
        } while (t != nullptr);
    }

private:
    Node* mHead = nullptr;
    Node* mTop = nullptr;
    size_t mSize = 0;
};

int main()
{
    int input;
    cin >> input;

    list l;
    for (int i = 1; i <= 4; ++i)
    {
        l.Push(input * i);
    }

    l.Print();
    
    return 0;
}

 


#define DIST ('A' - 11)

class list
{
public:

    struct Node
    {
        char value;
        Node* next;
    };

    void push(char d)
    {
        Node* buff = new Node;
        buff->value = d;
        buff->next = nullptr;

        if (size == 0)
            head = buff;
        else
            top->next = buff;
        top = buff;

        ++size;
    }

    void print()
    {
        Node* t = head;
        do
        {
            cout << t->value;
            t = t->next;
        } while (t != nullptr);
    }


private:
    Node* head = nullptr;
    Node* top = nullptr;
    size_t size = 0;
};


int main()
{
    int input;
    cin >> input;

    list l;
    for (int i = 0; i < 4; ++i)
    {
        l.push(input + i + DIST);
    }

    l.print();
    
    return 0;
}

 


char path[5] = { 0 };
char check[4] = { 0 };

int input = 0;

void Solve(int lev = 0)
{
    if (lev == input)
    {
        cout << path << endl;
        return;
    }

    for (int i = 0; i < 4; ++i)
    {
        if (check[i] == 1)
            continue;

        check[i] = 1;
        path[lev] = 'A' + i;
        Solve(lev + 1); 
        path[lev] = 0;
        check[i] = 0;
    }

    return;
}

int main()
{
    cin >> input;
    Solve();

    return 0;
}

 


class list
{
public:

	struct Node
	{
		char a;
		int b;
		Node* next;
	};

	void push(char c, int i)
	{
		Node* buff = new Node;
		buff->a = c;
		buff->b = i;
		buff->next = nullptr;

		if (size == 0)
		{
			head = buff;
		}
		else
		{
			tail->next = buff;
		}
		tail = buff;

		size++;
	}

	void printChar()
	{
		Node* t = head;
		for (int i = 0; i < size; ++i)
		{
			cout << t->a << " ";
			t = t->next;
		}
		cout << endl;
	}

	void printNum()
	{
		Node* t = head;
		while (t != nullptr)
		{
			cout << t->b << " ";
			t = t->next;
		}
		cout << endl;
	}

private:

	Node* head = nullptr;
	Node* tail = nullptr;
	size_t size = 0;
};

int main()
{
	int input;
	cin >> input;

	list l;
	for (int i = 0; i < input; ++i)
	{
		l.push('A' + i, i + 1);
	}

	l.printChar();
	l.printNum();

    return 0;
}

 


class Queue
{
public:
	struct Node
	{
		char data;
		Node* next;
	};

	void push(int d)
	{
		Node* buff = new Node;
		buff->data = d;
		buff->next = nullptr;

		if (size == 0)
		{
			head = buff;
		}
		else
		{
			tail->next = buff;
		}
		tail = buff;

		size++;
	}

	void pop()
	{
		if (size == 0) return;

		Node* buff = head->next;

		delete[] head;
		head = buff;

		size--;
	}


	void Print()
	{
		Node* buff = head;
		do
		{
			cout << buff->data << " ";
			buff = buff->next;
		} while (buff != nullptr);
	}

private:
	Node* head = nullptr;
	Node* tail = nullptr;
	int size = 0;
};

int main()
{
	Queue q;
	int input1, input2;
	cin >> input1 >> input2;

	for (int i = 0; i < input1; ++i)
	{
		char c;
		cin >> c;

		q.push(c);
	}

	for (int i = 0; i < input2; ++i)
	{
		q.pop();
	}

	q.Print();

    return 0;
}

 


int main()
{
    char buf[100] = { 0 };
    cin >> buf;

    bool find = false;
    int ret = 0;
    for (auto d : buf)
    {
        // 문자면
        if (d < '0' || '9' < d)
        {
            // 이전에 숫자를 찾은 경우면 종료
            if (find == true)
                break;
            // 문자만 찾아왔다면 다음 반복문 실행
            continue;
        }

        ret = ret * 10 + (d - '0');
    }

    cout << ret + 5;

    return 0;
}

 


class queue
{
public:
    struct Node
    {
        int x = 0;
        char y = 0;
    };

    void push(int i, char c)
    {
        if (max < size + 1) return;

        if (0 < size)
        {
            tail++;

            if (tail == max)
                tail = 0;
        }

        data[tail].x = i;
        data[tail].y = c;
        size++;
    }

    void pop()
    {
        if (size == 0) return;

        // 기존 값 초기화
        data[head] = Node();

        // head가 최대 인덱스를 넘었을 때
        head++;
        if (max <= head)
        {
            head = 0;
        }
        
        size--;
        return;
    }

    Node front()
    {
        return data[head];
    }

    bool empty()
    {
        if (size == 0) return true;
        return false;
    }

private:
    static const int max = 5;
    Node data[max];
    int head = 0;
    int tail = 0;
    int size = 0;
};

int main()
{
    queue q;

    int input = 0;
    cin >> input;
    for (int i = 0; i < input; i++)
    {
        int a;
        char b;
        cin >> a >> b;
        q.push(a, b);
    }

    while (q.empty() == false)
    {
        cout << q.front().x << " " << q.front().y << endl;
        q.pop();
    }

    return 0;
}

 


class queue
{
public:

	struct Node
	{
		int data;
		Node* next;
	};

	void Enqueue(int input)
	{
		Node* buff = new Node;
		buff->data = input;
		buff->next = nullptr;

		if (size == 0)
			head = buff;
		else
			tail->next = buff;

		tail = buff;
		++size;
	}

	void Dequeue()
	{
		if (size == 0)
			return;

		Node* temp = head->next;
		cout << head->data;

		memset(head, 0, sizeof(Node));
		delete[] head;
		
		head = temp;
		--size;
	}


private:

	Node* head = nullptr;
	Node* tail = nullptr;
	int size = 0;
};

int main()
{
	int input;
	cin >> input;

	queue q;
	for (int x = 0; x < input; ++x)
	{
		q.Enqueue(1);
		q.Enqueue(2);
		q.Enqueue(3);
		q.Dequeue();
		q.Dequeue();
		q.Dequeue();
	}

    return 0;
}

 


int board[4][4] = {
    3,5,1,4,
    2,2,1,1,
    0,1,2,3,
    3,1,3,1
};

int main()
{
    char input;
    cin >> input;

    for (int i = 0; i < 4; ++i)
    {
        int t;
        if ('0' <= input && input <= '3')
        {
            t = board[input - '0'][i];
        }
        if ('A' <= input && input <= 'D')
        {
            t = board[i][input - 'A'];
        }
        cout << t;
    }

    return 0;
}

 


int main()
{
    string input;
    cin >> input;

    int cnt = 0;
    for (auto d : input)
    {
        if (d == '<')
            ++cnt;
        if (d == '>')
        {
            if (--cnt < 0)
            {
                cout << "비정상";
                return 0;
            }
        }
        
    }

    if (cnt == 0)
        cout << "정상";
    else
        cout << "비정상";

    return 0;
}

 


int main()
{
    string text,cmd;
    int pos;
    cin >> text >> pos >> cmd;

    int max = text.size();

    for (auto d : cmd)
    {
        if (d == 'R')
            if (max < ++pos)
                pos = max;

        if (d == 'L')
            if (--pos < 0)
            pos = 0;
    }

    cout << pos;

    return 0;
}

 


class CircularQueue
{
public:

    struct Node
    {
        char data;
        Node* next;
    };

    void push(char d)
    {
        Node* buff = new Node;
        buff->data = d;

        if (size == 0)
            head = buff;
        if (0 < size)
            tail->next = buff;
        
        tail = buff;
        tail->next = head;

        ++size;
    }

    void pop()
    {
        if (size = 0) return;
        tail->next = head->next;
     
        memset(head, 0, sizeof(Node));
        delete[] head;

        head = tail->next;
    }

    char front()
    {
        return head->data;
    }


    void Rotation()
    {
        head = head->next;
        tail = tail->next;
    }

private:

    Node* head = nullptr;
    Node* tail = nullptr;
    int size = 0;
};

int main()
{
    CircularQueue q;

    q.push('B');
    q.push('I');
    q.push('A');
    q.push('H');

    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            q.Rotation();
        }
        cout << q.front();
        q.pop();
    }

    return 0;
}

 

int A[3][3] = {
    2,6,3,
    7,1,1,
    3,4,2
};

int B[2][4] = {
    6,4,2,4,
    1,1,5,8
};

int C[2][3] = {
    9,2,3,
    4,2,1
};

void Substitution(std::deque<int>& d, int* pi, size_t size)
{
    for (int i = 0; i < size; ++i)
    {
        d.push_back(*(pi + i));
    }
}


void MergeSort(int* data, int as, int ae, int be)
{
    // 1. Base case
    if (as == be)
        return;

    int bs = ae + 1;

    // 2. Merge
    MergeSort(data, as, (as + ae) / 2, ae);
    MergeSort(data, bs, (bs + be) / 2, be);

    // 3. Sort
    int tempAs = as;
    int buff[10] = { 0 };
    int inputIdx = 0;

    while (as <= ae && bs <= be)
    {
        if (data[as] <= data[bs])
        {
            buff[inputIdx++] = data[as++];
        }
        if (data[as] >= data[bs])
        {
            buff[inputIdx++] = data[bs++];
        }
    }
    
    while (as <= ae)
    {
        buff[inputIdx++] = data[as++];
    }
    while (bs <= be)
    {
        buff[inputIdx++] = data[bs++];
    }
    

    // 4. Copy
    // inputIdx => buff Size
    memcpy(data + tempAs, buff, inputIdx * sizeof(int));
}

int main()
{
    constexpr int lastIdxA = sizeof(A) / sizeof(int) - 1;
    MergeSort(*A, 0, lastIdxA / 2, lastIdxA);
    
    constexpr int lastIdxB = sizeof(B) / sizeof(int) - 1;
    MergeSort(*B, 0, lastIdxB / 2, lastIdxB);

    constexpr int lastIdxC = sizeof(C) / sizeof(int) - 1;
    MergeSort(*C, 0, lastIdxC / 2, lastIdxC);


    std::deque<int> dA;
    Substitution(dA, *A, lastIdxA + 1);

    std::deque<int> dB;
    Substitution(dB, *B, lastIdxB + 1);

    std::deque<int> dC;
    Substitution(dC, *C, lastIdxC + 1);

    int ret[3][3] = { 0 };
    int inputIdx = 0;

    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            if (j == 0)
            {
                ret[j][i] = dA.back();
                dA.pop_back();
            }
            if (j == 1)
            {
                ret[j][i] = dB.front();
                dB.pop_front();
            }
            if (j == 2)
            {
                ret[j][i] = dC.front();
                dC.pop_front();
            }
        }
    }
    ret[2][2] = dC.back();
    
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            cout << ret[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

'코딩 테스트 > 알고리즘 풀이' 카테고리의 다른 글

[LV15] 연습 문제  (0) 2025.05.24
[설계편] 코테 준비 문제  (0) 2025.05.24
[String편] 코테 준비 문제  (0) 2025.05.18
[LV10] 연습 문제  (0) 2025.05.12
[LV9] 연습 문제  (0) 2025.05.10
class string
{
public:

	string(const char* data)
	{
		mSize = strlen(data);
		mCapacity = mSize * 3;
		mData = new char[mCapacity];
		memcpy(mData, data, mSize + 1/*null character*/);
	}

	size_t length() const
	{
		return mSize;
	}

	void operator+=(const char* data)
	{
		//메모리 크기 체크
		size_t tokenSize = strlen(data);
		size_t newSize = mSize + tokenSize;
		size_t newCapacity = newSize * 3;

		// true : 메모리 크기 재할당
		if (mCapacity < newSize + 1/* null character*/)
		{
			// 메모리 복사
			char* newData = new char[newCapacity];
			memcpy(newData, mData, mSize); // 기존 데이터 복사
			memcpy(newData + mSize, data, tokenSize + 1); // 추가 데이터 복사

			// 기존 메모리 정리
			memset(mData, 0, mCapacity);
			delete[] mData;
			mData = newData;
		}
		// false : 기존 메모리 사용
		else
		{
			memcpy(mData + mSize, data, tokenSize + 1); // 추가 데이터 복사
		}

		// 멤버 변수 값 업데이트
		mCapacity = newCapacity;
		mSize = newSize;
	}

	char& operator[](int idx) const
	{
		return mData[idx];
	}

	friend std::ostream& operator<<(std::ostream& out, string& s)
	{
		out << s.mData;
		return out;
	}

private:

	char* mData;
	size_t mSize;
	size_t mCapacity;
};


int main()
{
	std::string strA("Hello");
	int len = strA.length();
	strA += " World";
	std::cout << strA[4];

	string strB("Hello");
	strB += " World~~~~~~~~~";
	strB[4] = 'a';
	std::cout << strB;

	return 0;
}

template<typename T>
class vector
{
public:
	vector()
	{
		mCapacity = 0;
		mSize = 0;
		mData = nullptr;
	}

	~vector()
	{
		if (mData != nullptr)
		{
			delete[] mData;
			mData = nullptr;
		}
	}

	void push_back(T data)
	{
		// Capacity 체크
		if (mCapacity < mSize + 1)
		{
			changeMemorySize((mSize + 1) * 3);
		}

		// 데이터 삽입
		mData[mSize] = data;
		++mSize;
	}

	const size_t size() const
	{
		return mSize;
	}

	T& operator[] (int i) const
	{
		return mData[i];
	}

	void clear()
	{
		memset(mData, 0, mSize * sizeof(T));
		mSize = 0;
	}

	void resize(const size_t size)
	{
		changeMemorySize(size);
	}

private:

	void changeMemorySize(size_t cap)
	{
		
		T* temp = new T[cap];

		// 메모리 크기를 수정할 때
		if (0 < mCapacity)
		{
			// 메모리가 더 커질때
			if (mCapacity < cap)
			{
				memcpy(temp, mData, sizeof(T) * mCapacity);
			}
			// 메모리가 더 작아졌을 때
			else
			{
				memcpy(temp, mData, sizeof(T) * cap);
			}

			// 기존 메모리 정리
			memset(mData, 0, mCapacity);
			delete[] mData;
		}
		
		// 기존 멤버 변수 업데이트
		mData = temp;
		mCapacity = cap;
	}

private:
	T* mData;
	size_t mCapacity;
	size_t mSize;
};

int main()
{
	vector<int> vec;
	vec.push_back(1);
	vec.push_back(2);
	vec.push_back(3);
	vec.push_back(4);
	vec.push_back(5);

	for (int i = 0; i < vec.size(); i++)
	{
		std::cout << vec[i];
	}

	vec.resize(10);

	for (int i = 0; i < vec.size(); i++)
	{
		vec[i] = i;
	}

	vec.clear();

	return 0;
}

'코딩 테스트 > 자료구조' 카테고리의 다른 글

힙 [Heap]  (0) 2022.07.29
스택 [Stack]  (0) 2022.01.27
Linked List  (0) 2022.01.26
Vector  (0) 2022.01.25

int main()
{
	char input[106];
	cin >> input;
	int size = strlen(input);

	int i = -1;
	while (++i < size - i - 1)
	{
		std::swap(input[i], input[size - i - 1]);
	}
	
	cout << input;

	return 0;
}

 


using namespace std;

int main()
{
	int input = -9463847412;
	//cin >> input;
	int ret = 0;

	while(input != 0)
	{
		// input의 뒷자리 추출 후 뒷자리 떼버리기
		int t = input % 10;
		input /= 10;

		// 더하기 전에 범위 체크, 
		// Overflow의 값을 저장할 수 없으니까, 맨 뒷자리와 그 나머지를 나누어서 비교
		// 양수
		if (INT_MAX / 10 < ret || INT_MAX / 10 == ret && INT_MAX % 10 < t)
		{
			cout << 0;
			return 0;
		}
		// 음수
		if (INT_MIN / 10 > ret || INT_MIN / 10 == ret && INT_MIN % 10 > t)
		{
			cout << 0;
			return 0;
		}

		// 문제 없다면 더하기
		ret = ret * 10 + t;
	}

	cout << ret;
	return 0;
}

 


char input[10'000'000];
char DAT[257] = { 0 };

int main()
{
	cin >> input;

	int i = 0;
	while (input[i] != 0)
	{
		++DAT[input[i++]];
	}

	i = 0;
	while (input[i] != 0)
	{
		if (DAT[input[i++]] == 1)
		{
			cout << i - 1;
			return 0;
		}
	}

	cout << -1;
	return 0;
}

 


char s[1000000] = { 0 };
char t[1000000] = { 0 };
char DATs[300] = { 0 };
char DATt[300] = { 0 };

int main()
{
	cin >> s >> t;

	if (strlen(s) != strlen(t))
	{
		cout << "false";
		return;
	}

	int i = 0;
	while (s[i] != 0 ||)
	{
		++DATs[s[i++]];
		++DATt[t[i++]];
	}

	for (int i = 'a'; i <= 'z'; ++i)
	{
		if (DATs[i] != DATt[i])
		{
			cout << "false";
			return;
		}
	}

	cout << "true";
	return 0;
}

 


char s[1000000] = "A man, a plan, a cansal: Panama";

int main()
{
	//cin >> s;
	char t[1000000] = { 0 };
	int inputIdx = 0;

	int spaceCnt = 0;
	for (int i = 0; i < strlen(s); ++i)
	{
		int c = s[i];

		if (c == ' ')
			++spaceCnt;

		if ((c < 'A' || 'z' < c) == (c < '0' || '9' < c))
		{
			continue;
		}

		if ('A' <= c && c <= 'Z')
			c += 'a' - 'A';

		t[inputIdx++] = c;
	}
	
	if (spaceCnt == strlen(s))
	{
		cout << "true";
		return 0;
	}

	int i = 0;
	do
	{
		if (t[i] != t[strlen(t) - i - 1])
		{
			cout << "false";
			return 0;
		}
	} while (++i < strlen(t) - i - 1);

	cout << "true";
	return 0;
}

 


char s[500] ={0};

int main()
{
	cin >> s;
	int idx = 0;

	// 1. 공백 무시
	while (s[idx] == ' ')
	{
		++idx;
	};
	
	// 2. 부호 확인
	int sign = 1;
	if (s[idx] == '-')
	{
		sign = -1;
		++idx;
	}

	// 3. 초반 0 무시
	while (s[idx] == '0')
	{
		++idx;
	};

	// 4. 숫자 저장 & 문자 확인
	int ret = 0;
	bool first = true;
	while (s[idx] != 0)
	{
		// 숫자 이외의 값이면 저장 종료
		if (s[idx] < '0' || '9' < s[idx])
			break;


		// 숫자 저장 전 범위 체크
		int t = (s[idx++] - '0') * sign;
		// 양수
		if (INT_MAX / 10 < ret || INT_MAX / 10 == ret && INT_MAX % 10 < t)
		{
			cout << INT_MAX;
			return 0;
		}
		// 음수
		if (INT_MIN / 10 > ret || INT_MIN / 10 == ret && INT_MIN % 10 > t)
		{
			cout << INT_MIN;
			return 0;
		}

		// 숫자 저장
		ret = ret * 10 + t;
	}

	cout << ret * sign;
	return 0;
}

 


char str[100000] = { 0 };
char token[100000] = { 0 };

int main()
{
	cin >> str >> token;

	int strSize = strlen(str);
	int tokenSize = strlen(token);

	bool ret = false;
	int i = 0;
	for (; i < strSize - tokenSize + 1; ++i)
	{
		if (strncmp(str + i, token, tokenSize) == 0)
		{
			ret = true;
			break;
		}
	}

	cout << (ret ? i : -1);

	return 0;
}

 


int main()
{
	string strs[] = { "dog", "racecar", "car" };
	int size = sizeof(strs) / sizeof(string);

	sort(strs, &(strs[size]));

	int i;
	for (i = 0; strs[0][i] == strs[size - 1][i]; ++i);

	cout << strs[0].substr(0, i);
	return 0;
}

'코딩 테스트 > 알고리즘 풀이' 카테고리의 다른 글

[설계편] 코테 준비 문제  (0) 2025.05.24
[LV14] 연습 문제  (0) 2025.05.21
[LV10] 연습 문제  (0) 2025.05.12
[LV9] 연습 문제  (0) 2025.05.10
[LV8] 복습 문제  (0) 2025.05.09

struct BBQ
{
    int a;
    int b;
};

int main()
{
    BBQ* bbq = new BBQ;
    cin >> bbq->a >> bbq->b;

    cout << bbq->a + bbq->b;
    return 0;
}

 


int main()
{
    char *a, *b, *c;
    a = new char;
    b = new char;
    c = new char;

    cin >> *a >> *b >> *c;

    //isupper islower
    if ('A' <= *a && *a <= 'Z')
        if ('A' <= *b && *b <= 'Z')
            if ('A' <= *c && *c <= 'Z')
            {
                cout << "모두 대문자";
                return 0;
            }

    cout << "소문자 있음";
    return 0;
}

 


struct Node
{
    int a;
    Node* p1;
    Node* p2;
};

int main()
{
    Node* head = new Node;
    head->a = 3;   
    head->p1 = new Node;
    head->p2 = new Node;

    head->p1->a = 7;

    head->p2->a = 6;
    head->p2->p1 = new Node;

    head->p2->p1->a = 2;

    return 0;
}

 


struct Node
{
    char a;
    Node* p1;
    Node* p2;
};

int main()
{
    Node* head = new Node;
    head->a = 'A';
    head->p1 = new Node;
    head->p2 = new Node;

    head->p1->a = 'B';
    head->p1->p1 = new Node;
    head->p1->p2 = new Node;
    
    head->p1->p1->a = 'D';
    head->p1->p2->a = 'E';

    head->p2->a = 'C';

    char cmd[100] = { 0 };
    cin >> cmd;

    Node* t = head;
    int i = 0;
    do
    {
        if (cmd[i] == 'L')
            t = t->p1;
        if (cmd[i] == 'R')
            t = t->p2;
    } while (cmd[++i] != 0);

    cout << t->a;
    return 0;
}

 


struct Node
{
    int a;
    Node* p = nullptr;
};

int main()
{
    Node* head = new Node;
    head->p = new Node;

    head->p->a = 3;
    head->p->p = new Node;

    head->p->p->a = 5;
    head->p->p->p = new Node;

    head->p->p->p->a = 4;
    head->p->p->p->p = new Node;

    head->p->p->p->p->a = 2;

    do
    {
        head = head->p;
        cout << head->a << " ";
    } while (head->p != nullptr);

    return 0;
}

 


struct Node
{
    char a;
    Node* p = nullptr;
};

int main()
{
    char str[] = "QTPKQ";

    Node* head = new Node;
    Node* t = head;

    for (int i = 0; i < 5; ++i)
    {
        t->p = new Node;
        t = t->p;
        t->a = str[i];
    }

    cout << t->a;

    return 0;
}

 


struct Node
{
    string name = { 0 };
    Node* Love1 = nullptr;
    Node* Love2 = nullptr;
};

int main()
{
    Node* head = new Node;
    Node* boss = new Node;
    Node* wife = new Node;
    Node* son = new Node;
    Node* gf = new Node;
    Node* bf = new Node;


    boss->name = "boss";
    boss->Love1 = wife;
    boss->Love2 = son;

    wife->name = "wife";
    wife->Love1 = boss;
    wife->Love2 = son;

    son->name = "son";
    son->Love1 = gf;
    son->Love2 = bf;

    gf->name = "girlfriend";
    gf->Love1 = son;
    gf->Love2 = bf;

    bf->name = "boyfriend";
    bf->Love1 = gf;
    bf->Love2 = nullptr;

    head = boss;
    cout << head->Love2->Love1->name << " " << head->Love2->Love2->name;

    return 0;
}

 


int input = 0;

int main()
{
    cin >> input;

    int extract[2] = { 0 };
    int i = 1;
    while(0 <input)
    {
        if (i == 2 || i == 4)
        {
            extract[i / 2 - 1] = input % 10;
        }
        input /= 10;
        ++i;
    }

    cout << extract[1] * 10 + extract[0] + 5;

    return 0;
}

 


char board[4][4] = { 0 };

int main()
{
    for (int i = 0; i < 16; ++i)
    {
        cin >> *((*board) + i);
    }

    for (int i = 0; i < 4; ++i)
    {
        int ret = 0;
        for (int j = 0; j < 4; ++j)
        {
            if (board[j][i] != '#') 
                ++ret;
        }
        cout << ret << " ";
    }

    return 0;
}

 


int main()
{
    string input;
    cin >> input;

    int cntB = 0;
    for (auto d : input)
    {
        if (d == 'B')
            ++cntB;
        else
            --cntB;

        if (cntB < 0)
        {
            cout << "짝이 안맞음";
            return 0;
        }
    }

    if (cntB != 0)
        cout << "짝이 안맞음";
    else 
        cout << "짝이 맞음";

    return 0;
}

 


int board[3][3] = {
    0,5,4,
    3,0,0,
    0,0,1
};

void Rotation()
{
    for (int i = 0; i < 3; ++i)
    {
        for (int j = i; j < 3; ++j)
        {
            std::swap(board[i][j], board[j][i]);
        }
        std::reverse(board[i], board[i] + 3);
    }
}

int main()
{
    int input;
    cin >> input;

    for (int i = 0; i < input; ++i)
    {
        Rotation();
    }

    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
    
    return 0;
}

 


char input[16] = {0};

int main()
{
    cin >> input;

    char* p = input;
    while(*p != 0)
    {
        char t[6] = { 0 };
        memcpy_s(t, sizeof(t), p, 5);
        cout << t << endl;

        p += 5;
    }

    return 0;
}

 


int number[6] = { 3,7,4,0,9,6 };
char input[] = "mxmmxx";

// 닫힌 구간 [ as <= idx <= be ]
void sort(int as, int ae, int be)
{
    int bs = ae + 1;

    // Base case
    if (as == be) return;

    // 분할
    sort(as, (as + ae) / 2, ae);
    sort(bs, (bs + be) / 2, be);

    // 정렬
    int tas = as; // 마지막 복사를 위한 임시 저장 값
    int arrSize = be - as + 1;
    int t[10] = { 0 };
    int i = 0;
    while (as <= ae && bs <= be)
    {
        if (number[as] < number[bs])
            t[i++] = number[as++];
        else
            t[i++] = number[bs++];
    }

    // a파트를 모두 탐색했을 때
    while (bs <= be)
        t[i++] = number[bs++];

    // b파트를 모두 탐색했을 때
    while (as <= ae)
        t[i++] = number[as++];

    // 데이터 이동
    int a = memcpy_s(&(number[tas]), arrSize * sizeof(int), t, arrSize * sizeof(int));
}

int main()
{
    sort(0, 5 / 2, 5);

    int m = 0, x = 5;
    for (auto d : input)
    {
        if (d == 'm')
            std::cout << number[m++] << " ";
        if (d == 'x')
            std::cout << number[x--] << " ";
    }

    return 0;
}

 


char path[4] = { 0 };
void Func(int level, const int n)
{
	// Base case
	if (level == n)
	{
		cout << path << endl;
		return;
	}

	for (int i = 1; i < 7; ++i)
	{
		path[level] = i + '0';
		Func(level + 1, n);
		path[level] = 0;
	}

	return;
}

int main()
{
	int n; 
	cin >> n;
	Func(0, n);

	return 0;
}

 


 

class Shape
{
public:
	Shape()
	{
		type_ = 1;
		len_ = 1;
		rectCnt_++;
	}

	Shape(int type, double len)
		: type_(type), len_(len) 
	{	
		if (type_ == 1) rectCnt_++;
		if (type_ == 2) circleCnt_++;
	}

	~Shape()
	{
		if (type_ == 1) rectCnt_--;
		if (type_ == 2) circleCnt_--;
	}

	static const int GetRectCount()
	{
		return rectCnt_;
	}

	static const int GetCircleCount()
	{
		return circleCnt_;
	}

	const double GetArea() const
	{
		// 정사각형
		if (type_ == 1)
		{
			return len_ * len_;
		}
		// 원
		if (type_ == 2)
		{
			return len_ * len_ * PI;
		}
	}

private:
	const double PI = 3.14;

	static int rectCnt_;
	static int circleCnt_;

	int type_; // 1 : 정사각형, 2 : 원
	double len_; // 정사각형의 경우 한 변의 길이, 원의 경우 반지름
};

int Shape::rectCnt_ = 0;
int Shape::circleCnt_ = 0;

 


class Array
{
public:
	Array() = default;
	Array(int count)
		:count_(count)
	{
		ary_ = new int[count_];
		PutData();
	}
	~Array()
	{
		delete[] ary_;
	}

	void PrintArray() 
	{
		for (int i = 0; i < count_; ++i)
		{
			cout << ary_[i] << " ";
		}
		cout << endl;
	}

private:
	void PutData()
	{
		for (int i = 0; i < count_; ++i)
		{
			ary_[i] = rand() % 10;
		}
	}

private:
	int count_;
	int* ary_;
};

int main()
{
	srand(time(NULL));

	Array arr1(3);
	Array arr2(5);

	arr1.PrintArray();
	arr2.PrintArray();

	return 0;
}

'코딩 테스트 > 알고리즘 풀이' 카테고리의 다른 글

[LV14] 연습 문제  (0) 2025.05.21
[String편] 코테 준비 문제  (0) 2025.05.18
[LV9] 연습 문제  (0) 2025.05.10
[LV8] 복습 문제  (0) 2025.05.09
[LV8] 연습 문제  (0) 2025.05.07

+ Recent posts