알고리즘
백준 2617번 구슬 찾기 C++
영춘권의달인
2022. 3. 1. 11:02
자기보다 가벼운 것과 무거운 것 두 경우의 그래프를 만들고, 둘 중 하나라도 자기의 자식의 수가 n/2보다 크다면 중간이 될 수 없다.
#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 <unordered_map>
#include <unordered_set>
#include <iomanip>
using namespace std;
using ll = long long;
int hs = 0;
int ls = 0;
vector<vector<int>> light(100, vector<int>());
vector<vector<int>> heavy(100, vector<int>());
vector<bool> visited1(100, false);
vector<bool> visited2(100, false);
void dfs1(int n) {
for (auto a : heavy[n]) {
if (!visited1[a]) {
visited1[a] = true;
dfs1(a);
hs++;
}
}
}
void dfs2(int n) {
for (auto a : light[n]) {
if (!visited2[a]) {
visited2[a] = true;
dfs2(a);
ls++;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int h, l;
cin >> h >> l;
light[h].push_back(l);
heavy[l].push_back(h);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
dfs1(i);
dfs2(i);
if (hs > n / 2 || ls > n / 2) ans++;
for (int j = 1; j <= n; j++) {
visited1[j] = false;
visited2[j] = false;
}
hs = 0;
ls = 0;
}
cout << ans;
};