사회망 서비스(SNS)
사회망 서비스(SNS)
어떤 걸 사용하나요?
모든 두 정점 사이에 이들을 잇는 경로가 존재하면서, 사이클이 존재하지 않는다. 자신의 모든 친구들이 얼리 아답터인 경우 중 최소값을 구해야 한다. DP를 사용해서 트리 구조에서 리프 노드부터 계산하도록 한다. 이를 위해 각 노드 활성화 상태를 기록해야 한다. 정점 개수가 최대 1,000,000개이기 때문에 배열로 구현하고 dp[i 번 노드][활성화/비활성화] 이런 식으로 저장해두고 각 경우를 하나씩 올라오면서 계산한다.
어떻게 구현하나요?
- 1번 노드를 기준으로 재귀
- 상태 - [내 노드][활성화(1)/비활성화(0)][부모노드 활성화/비활성화]
- 근데 자식이 정해진게 아님.
- 트리를 먼저 만들어주기.
- root 정하고 각 노드마다 자식 세팅
- dp[i]
- graph[i]의 자식 노드들의 인덱스(a, b)를 가져온다.
- dp[i][1] = min(dp[a][1], dp[a][0]) + min(dp[b][1], dp[b][0]) + 1;
- dp[i][0] = dp[a][1] + dp[b][1];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <vector>
#define TRUE 1
#define FALSE 0
#define INF 1e9
using namespace std;
vector<vector<int>> graph;
vector<vector<int>> tree;
vector<vector<int>> dp;
vector<bool> visited;
void MakeTree(int root){
visited[root] = true;
for(int val : graph[root]){
if(visited[val] == false){
tree[root].push_back(val);
visited[val] = true;
MakeTree(val);
}
}
}
int solve(int cur, int curState){
if(tree[cur].size() == 0){
dp[cur][curState] = curState;
return curState;
}
// 메모제이션
if(dp[cur][curState] != -1){
return dp[cur][curState];
}
// 초기화
dp[cur][curState] = curState;
int sum = 0;
bool isTrue = false;
for(int i = 0; i < tree[cur].size(); i++){
int next = tree[cur][i];
int trueVal = solve(next, TRUE);
int falseVal = solve(next, FALSE);
if(curState == TRUE){
sum += min(trueVal, falseVal);
}else{
sum += trueVal;
}
}
//cout << cur << "(" << curState << " , " << tree[cur].size() << ") : " << sum << '\n';
dp[cur][curState] += sum;
return dp[cur][curState];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
graph = vector<vector<int>>(n+1, vector<int>());
tree = vector<vector<int>>(n+1, vector<int>());
dp = vector<vector<int>>(n+1, vector<int>(2, -1));
visited = vector<bool>(n+1, false);
for(int i = 0; i < n-1; i++){
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
MakeTree(1);
cout << min(solve(1, 0), solve(1, 1)) << '\n';
// cout << "====================\n";
// for(int i = 1; i <= n; i++){
// cout << i << "| " << dp[i][TRUE] << ", " << dp[i][FALSE] << '\n';
// }
return 0;
}
This post is licensed under CC BY 4.0 by the author.
