알고리즘
백준 24230번 트리 색칠하기 C++
영춘권의달인
2023. 2. 18. 11:58
https://www.acmicpc.net/problem/24230
24230번: 트리 색칠하기
정점이 $N$개인 트리가 있다. 정점에는 1부터 $N$까지 번호가 붙어있다. 트리의 루트는 항상 1번 정점이며 맨 처음에는 모든 정점이 하얀색으로 칠해져 있는 상태이다. 하나의 정점에 색칠하면 해
www.acmicpc.net
부모와 자식의 색이 다르다면 그부분에서 색을 칠해야 하므로 cnt 1 증가
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n;
int cnt = 0;
vector<vector<int>> graph;
vector<bool> visited;
vector<int> color;
void Dfs(int currNode, int lastColor) {
visited[currNode] = true;
if (color[currNode] != lastColor) cnt++;
for (auto nextNode : graph[currNode]) {
if (visited[nextNode]) continue;
Dfs(nextNode, color[currNode]);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
graph = vector<vector<int>>(n + 1, vector<int>());
visited = vector<bool>(n + 1, false);
color = vector<int>(n + 1);
for (int i = 1; i <= n; i++) {
cin >> color[i];
}
for (int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
Dfs(1, 0);
cout << cnt;
}