ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1067) N
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (180) N
      • Unreal (69)
      • Unity (100) N
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • C++
  • 그래픽스
  • Unity
  • 문자열
  • SQL
  • 배열
  • 프로그래머스
  • c#
  • 함수
  • 언리얼
  • 유니티
  • 파이썬
  • C
  • string
  • 백준
  • 포인터
  • 티스토리챌린지
  • 오블완
  • 클래스
  • 알고리즘

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

코딩테스트/백준

[골4] 1647 - 도시 분할 계획

2023. 10. 23. 16:03
#include <iostream>
#include <algorithm>
#include <vector>

#define FAST_IO() \
{\
	ios::sync_with_stdio(false);\
	cin.tie(NULL); \
	cout.tie(NULL); \
}\

using namespace std;
using IntPair = pair<int, int>;
using NodePair = pair<IntPair, int>;

vector<NodePair> graph;
int parent[100001];

int Find(int x)
{
	if (parent[x] == x)
		return x;

	else
		return parent[x] = Find(parent[x]);
}

void Union(int a, int b)
{
	a = Find(a), b = Find(b);
	parent[a] = b;
}

bool IsCycle(int a, int b)
{
	return (Find(a) == Find(b));
}

int main()
{
	FAST_IO();

	vector<int> res;
	int n, m;
	cin >> n >> m;

	// 부모
	for (int i = 1; i <= n; i++)
		parent[i] = i;

	for (int i = 0; i < m; i++)
	{
		int a, b, c;
		cin >> a >> b >> c;
		graph.push_back({ {a, b}, c });
	}
	// 비용(거리값) 순으로 오름차순 정렬
	sort(graph.begin(), graph.end(), [&](NodePair a, NodePair b)
		{
			return a.second < b.second;
		});

	for (int i = 0; i < graph.size(); i++)
	{
		auto node = graph[i];
		int a = node.first.first;
		int b = node.first.second;
		int c = node.second;

		if (!IsCycle(a, b))
		{
			Union(a, b);
			res.push_back(c);
		}
	}
	int sum = 0;

	for (int i = 0; i < res.size() - 1; i++)
		sum += res[i];

	cout << sum;
	return 0;
}
저작자표시 (새창열림)

'코딩테스트 > 백준' 카테고리의 다른 글

[골3] 2473 - 세 용액  (0) 2023.10.23
[골3] 2623 - 음악프로그램  (0) 2023.10.23
[실2] 2512 - 예산  (0) 2023.10.20
[실3] 10158 - 개미  (0) 2023.10.20
[골4] 1715 - 카드 정렬하기  (0) 2023.10.20
    '코딩테스트/백준' 카테고리의 다른 글
    • [골3] 2473 - 세 용액
    • [골3] 2623 - 음악프로그램
    • [실2] 2512 - 예산
    • [실3] 10158 - 개미
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바