https://programmers.co.kr/learn/courses/30/lessons/43162

 

코딩테스트 연습 - 네트워크

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있��

programmers.co.kr

문제

입력&출력


문제해석

이차원배열이 주어진다. 서로 연결되어있으면 1 아니면 0으로 주어지며 자기자신과는 연결되었다라고 친다.

ex) (0,1) = 1 and (1,0)=1 이면 서로 연결 , (0,1) = 0 and (1,0)=0 이면 연결X

먼저 엑셀로 다음과 같이 구조화함 

1)DFS/BFS는 항상 visit배열, 노드는 항상 벡터로표현!!

상기 그림의 하단의 노드번호 및 연결된 노드는 Vector로 구현 

   vector<int> v[200];
   for (int i = 0; i < computers.size(); i++)
   {
      for (int j = 0; j < computers[i].size(); j++)
      {
         if (computers[i][j] == 1)
            v[i].push_back(j);
      }
   }

2) BFS 구현 

   for (int i = 0; i < n; i++)
   {
      if (v[i].size() == 0)
         continue;
      if (vi[i])
         continue;
      queue<int> q;
      q.push(i);
      vi[i] = true;
      while (!q.empty())
      {
         int x = q.front();
         q.pop();

         for (int w = 0; w < v[x].size(); w++)
         {
            if (!vi[v[x][w]])
            {
               vi[v[x][w]] = true;
               q.push(v[x][w]);
            }
         }
      }
      answer++;
   }

BFS을 이용해 한번에 모든 노드를 순회하면 네트워크는 = 1 

그 외에 여러번 순회 (= 끊겨있는 노드일때) answer++ 해주며 끊긴만큼 네트워크를 늘림.

 

난이도

★☆


실수

스스코드

#include <string>
#include <vector>
#include <queue>

using namespace std;

int solution(int n, vector<vector<int>> computers) {
   int answer = 0;
   vector<int> v[200];
   bool vi[200] = { false, };

   for (int i = 0; i < computers.size(); i++)
   {
      for (int j = 0; j < computers[i].size(); j++)
      {
         if (computers[i][j] == 1)
            v[i].push_back(j);
      }
   }

   for (int i = 0; i < n; i++)
   {
      if (v[i].size() == 0)
         continue;
      if (vi[i])
         continue;
      queue<int> q;
      q.push(i);
      vi[i] = true;
      while (!q.empty())
      {
         int x = q.front();
         q.pop();

         for (int w = 0; w < v[x].size(); w++)
         {
            if (!vi[v[x][w]])
            {
               vi[v[x][w]] = true;
               q.push(v[x][w]);
            }
         }
      }
      answer++;
   }
   return answer;
}

 

 

https://programmers.co.kr/learn/courses/30/lessons/42628

문제

입력&출력


문제해석&접근버

우선 문제에 우선순위'큐' 라서 큐를 써야하나? 라는 생각을함.

하지만 최소값, 최대값을 입력에 맞게 빼려면 (앞,뒤로) 큐로 구현하면 복잡해질 것(상황에 따라서 오름차순, 내림차순 정렬을 해야함) 예상

따라서 List로 구현!!

 

난이도

☆ 

다시 풀어볼만함


실수

'I' (Input) 경우, 최소/최대값 경우 총 3가지 경우가 입력이 되는데, 최소값제거->sort,최대값제거->sort 해줬는데 Input->sort를 안해주는 실수를 함 

만약 Operations에서 마지막의 경우가 "I n" 라면 마지막 값 입력 후 sort를 해줘야 최대값, 최소값을 출력함. 

 

스스코드

 

#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <algorithm>
#include <string>

using namespace std;
vector<int> solution(vector<string> operations) {
    list<int> l;
    vector<int> answer;
	for (int i = 0; i < operations.size(); i++)
	{
		string str = operations[i];

		//삽입
		if (str[0] == 'I')
		{
			string strNum = "";
			int parseInt;
			for (int j = 2; j < str.size(); j++)
			{
				strNum += str[j];
			}
			parseInt = stoi(strNum); //string -> int 변경함수
			l.push_back(parseInt); l.sort();
		}
		//제거
		else 
		{
			if (str[2] == '-')
			{
                if (l.empty()) continue;
				l.sort();
				l.pop_front();
			}
			else
			{
                if (l.empty()) continue;
				l.sort();
				l.pop_back();
			}
		}
	} 
    
    if(l.size() > 1 ) 
    {
        answer.push_back(l.back());
		answer.push_back(l.front());
    }
    //만약 최대값 최소값을 구분할 수 없는 0개,1개 일 경우
    else
    {
        answer.push_back(0);
        answer.push_back(0);
    } 
    return answer;
}

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

문제

가로와 세로에서 낱말이 있으면 모두 추출해서 사전식으로 가장 앞서 있는 낱말을 찾는다.

 

입력 & 출력

R*C는 최대 20x20 --> 완탐이다.

 

주관적인 문제난이도 : 프로그래머스 Lv2 정도, ★★☆

 

SOL)

문제 보자마자 Set 자료구조를 쓰면 편리하다고 생각했음(자동정렬, 중복제거) 하지만 자료 구조에 넣을 때 iterator로 순회한 후 중복체크하는것 연습하기 위해 그냥 Vecotor로 구현 ! 

 

예외처리1) 가로 세로 순회하며 '#'을 만날 때 Vector에 넣어준다. 그때 적재했던 단어의 길이가 1보다 작으면 vector에 넣지 않고 해당 적재했던 값을 초기화한다.

 

소스코드

 

C++

#include <iostream>
#include <vector> 
#include <string>
#include <algorithm>

using namespace std;
char arr[20][20];
string str;
int n, m;
vector<string> v;
void input()
{

	cin >> n;
	cin >> m;
	//input()
	for (int i = 0; i < n; i++)
	{
		string s;
		cin >> s;
		for (int j = 0; j < m; j++)
		{	
			arr[i][j] = s[j];
		}
	}

}
void sol()
{ 
	vector<string>::iterator it;
	//가로
	for (int i = 0; i < n; i++)
	{ 
		string sumStr=""; 
		for (int j = 0; j < m; j++)
		 {
			if (arr[i][j] == '#')
			{
				//문자있을때
				if (sumStr.size() > 1)
				{
				 
                 	v.push_back(sumStr);
                	sumStr = "";
               	 	continue; 
				}
				else 
				{
					sumStr = "";
					continue;
				}
				
			}
			else
			{ 
				sumStr += arr[i][j];
			}
			if (j == m - 1 && sumStr.size() > 1)
			{
				sumStr += arr[i][j];
				v.push_back(sumStr); 
                sumStr = "";
 
			}
		} 
	}

	//새로
 
	for (int i = 0; i < m; i++)
	{
		string sumStr = "";
	 
		for (int j = 0; j < n; j++)
		{

			if (arr[j][i] == '#')
			{
				if (sumStr.size()>1)
				{ 
                  v.push_back(sumStr);
                  sumStr = "";
                  continue;
				 
				}
				else
				{
					sumStr = ""; 
					continue;

				}
				
			}
			else
			{
		 
				sumStr += arr[j][i];
			}

			if (j == n - 1 && sumStr.size() > 1)
			{
			 
             v.push_back(sumStr);
             sumStr = "";

			}
		}
	} 
	sort(v.begin(), v.end());
	
	 
}
int main()
{
	string answer;
	input();
	sol();
	if(v.size()>0)
	cout << v[0] << endl;
	
	return 0;


}

 

Java

package Z_ShinHanCard_Prepare;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
 
 
public class 백준1706_크로스워드 {
	static int R;
	static int C;
	static char crossWord [][];
	static Set<String> wordList = new HashSet<String>();
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		String input = br.readLine();
		StringTokenizer st= new StringTokenizer(input);
		R= Integer.parseInt(st.nextToken());
		C= Integer.parseInt(st.nextToken());
		crossWord= new char[R][C];
		//StringBuilder sb;
		for (int i=0; i<R; i++) {
			input = br.readLine();
			for (int j=0; j<C; j++) {
				crossWord[i][j]=input.charAt(j);
			}
		}
		
		
		for (int i=0; i<R; i++) {
		//	sb= new StringBuilder();
			String tempStr = "";
			for(int j=0; j<C; j++) {
				if (crossWord[i][j]=='#') {
					if (tempStr.length()>1)
						{
						wordList.add(tempStr.toString());
						
						}
					tempStr = "";
				}
				else {
					tempStr += crossWord[i][j];
					
				}
			}
			if (tempStr.length()>1)
			{
			wordList.add(tempStr);
			
			}
		}
		for (int j=0; j<C; j++) {
			//sb= new StringBuilder();
			String tempStr = "";
			for (int i=0; i<R;i++) {
				if (crossWord[i][j]=='#') {
					if (tempStr.length()>1)
					{
					wordList.add(tempStr);
					
					}
					  tempStr = "";
				}
				else {
					tempStr += crossWord[i][j];
				}
			}
			if (tempStr.length()>1)
			{
			wordList.add(tempStr);
			
			}
		}
		ArrayList<String> list= new ArrayList<String>();
		for (String s: wordList) {
			list.add(s);
		}
		Collections.sort(list);
		
		System.out.println(list.get(0));
	}

}

폴더 경로 가져오는 코드 

m_DbfData.clear();
BROWSEINFO BrInfo;
TCHAR szBuffer[512];// 경로저장 버퍼 

::ZeroMemory(&BrInfo, sizeof(BROWSEINFO));
::ZeroMemory(szBuffer, 512);

BrInfo.hwndOwner = GetSafeHwnd();
BrInfo.lpszTitle = _T("파일이 저장될 폴더를 선택하세요");
BrInfo.ulFlags = BIF_NEWDIALOGSTYLE | BIF_EDITBOX | BIF_RETURNONLYFSDIRS | TBIF_TEXT;
LPITEMIDLIST pItemIdList = ::SHBrowseForFolder(&BrInfo);
::SHGetPathFromIDList(pItemIdList, szBuffer);   

//path 경로 저장
CString inputPath =_T("");  
inputPath.Format(_T("%s"), szBuffer);

 

경로 옵션

BrInfo.ulFlags = BIF_NEWDIALOGSTYLE | BIF_EDITBOX | BIF_RETURNONLYFSDIRS | TBIF_TEXT;

BIF_BROWSEFORCOMPUTER    : 네트워크의 컴퓨터만 선택가능

BIF_BROWSEFORPRINTER        : 프린터만 선택가능

BIF_BROWSEINCLUDEFILES      : 파일도 표시

BIF_DONTGOBELOWDOMAIN  : 네트워크의 컴퓨터를 표시하지 않는다

BIF_EDITBOX                      : 에디트 박스를 표시한다

BIF_RETURNFSANCESTORS     : 네트워크의 컴퓨터만 선택가능

BIF_RETURNONLYFSDIRS        : 폴더만 선택가능

BIF_STATUSTEXT                  : 스테이터스 텍스트를 표시한다

BIF_VALIDATE                     : 부정 입력시에, BFFM_VALIDATEFAILED 이벤트

 

 

문자열(CString)에서 특정한 문자 찾기

 

  • Find() 함수 
    • 문자열에서 특정한 문자의 순서를 리턴함, 단 특정한 문자가 없을지 -1을 리턴함
	CString temp = _T("abc");
	int tempint = temp.Find(_T("a")); //0
	tempint = temp.Find(_T("b")); //1
	tempint = temp.Find(_T("c")); //2
	tempint = temp.Find(_T("d")); //-1 

 

int <-> CString

int nNum = 5;

CString strNum

 

char -> int

nNum = atoi(strNum);

 

CString -> int

strNum.Format(_T("%d"), nNum); 

 

int <-> CString 

nNum = _ttoi(strNum);  

 

%c : 단일문자

%d : 부호있는 10진 정수

%i  : 부호있는 10진 정수, %d와 같음

%f  : 부호있는 실수 (float 아니다 double이고 소수점은 기본 6자리까지 표시됨)

%s : 문자열

%o : 부호없는 8진 정수

%u : 부호없는 10진 정수

%x : 부호없는 16진 정수(소문자)

%X : 부호없는 16진 정수(대문자)

%e : e 표기법에 의한 실수

%p : 포인트

%#010x : 주소

 

 

CString <-> const char*

[ CString -> const char* ]

CString str1 = _T("안녕하세요");
const char* str2;
str2 = (CStringA) str1;


[ const char* -> CString ]

const char* str1 = "안녕하세요";
CString str2;
str2 = (CString)str1; 

 

CString <-> wchar_t

 // CString -> wchar_t *  
 CStringW aaa(_T("hello!"));
 wchar_t *a = (wchar_t *)aaa.GetBuffer();


//비추
 wchar_t wTemp[1024] = L"\0";
 MultiByteToWideChar(CP_ACP, 0, m_szNotice,m_szNotice.GetLength(),wTemp,1024);

 
 // wchar_t *  -> CString 변환
 wchar_t *aaa = L"Hello, World!";
 CString temp(aaa);   
 m_szText = temp;

 

'MFC' 카테고리의 다른 글

[MFC] 현재 실행파일(.exe)의 위치 반환  (0) 2020.07.06
[MFC] CString에서 특정한 문자 찾기 Find함수  (0) 2020.07.02
C++ MFC CString  (0) 2020.06.26
[MFC] 응답없음 처리  (0) 2020.06.25
[MFC] ProgressBar  (0) 2020.06.25

+ Recent posts