๋ฌธ์
ํ์ด
๊ฒฐ๊ตญ ์ด๋ถ๊ทธ๋ํ๋ฅผ ๋ง๋๋ ๋ฌธ์ ๋ค.
5
1 3
1 5
2 1 4
1 3
1 2
์ ๊ฒฝ์ฐ๋ฅผ ์๋ก ๋ค์.
์ซ์ดํ๋ ๊ด๊ณ๋ฅผ ์ ํฅ๊ทธ๋ํ๋ก ๊ทธ๋ฆฌ๋ฉด ์ด๋ ๊ฒ ๋ํ๋ผ ์ ์๋ค.
์ฌ๊ธฐ์ 1๋ฒ๋ ธ๋๋ถํฐ ์ฒญํ์ ๋ค์ด๊ฐ๋ค๊ณ ๊ฐ์ ํ์. ๊ทธ๋ ๊ฒ ๋๋ค๋ฉด 1๋ฒ ๋ ธ๋๋ 3๋ฒ์ ์ซ์ดํ๋ฏ๋ก 3๋ฒ์ ๋ฌด์กฐ๊ฑด ๋ฐฑํ์ ๋ค์ด๊ฐ๊ฒ ๋๋ค.
3๋ฒ์ ๊ธฐ์ค์ผ๋ก 3๋ฒ๋ ธ๋๋ 4๋ฒ์ ์ซ์ดํ๋ฏ๋ก 4๋ฒ๋ ธ๋๋ ์ฒญํ์ ๋ค์ด๊ฐ๊ฒ ๋๋ค.
4๋ฒ๋ ธ๋๋ ์ซ์ดํ๋ ๋ ธ๋๊ฐ ์์ผ๋ฏ๋ก, ๋ค์ 2๋ฒ๋ ธ๋๋ถํฐ ์ฒญํ์ ๋ฃ๊ณ ์์ํ๊ฒ ๋๋ค๋ฉด
๋ค์๊ณผ ๊ฐ์ ๊ทธ๋ํ๊ฐ ๊ทธ๋ ค์ง๊ฒ ๋๋ค.
์ซ์ดํ๋ ์ฌ๋์ด ํ๋๋ ์๋ ๊ฒฝ์ฐ๋ ์์ผ๋ฏ๋ก, ํ๋ช ๋ง ์ซ์ดํ๋์ฌ๋์ด ํ๋ช ์๋ ๊ฒฝ์ฐ๊ฐ ํ์์ ๊ธฐ์ค์์ ๊ฐ์ฅ ์ค๋ ๊ฑธ๋ฆฌ๋ ๊ฒฝ์ฐ๋ค.
๋ชจ๋ ๋ ธ๋๋ฅผ ํ๋ฒ์ฉ๋ง ๋ฐฉ๋ฌธํ๋ฉด ๋๋ฏ๋ก O(N)์ด๋ค.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int> > v(101);
int n, vis[101], blue[101], white[101], bans, wans;
int main() {
cin>>n;
for(int i=1; i<=n; i++) {
int a; cin>>a;
while(a--) {
int b; cin>>b;
v[i].push_back(b);
}
}
for(int i=1; i<=n; i++) {
if(vis[i]) continue;
vis[i] = 1;
blue[i] = 1; bans += 1;
queue<int>q;
q.push(i);
while(!q.empty()) {
int cur = q.front(); q.pop();
for(auto e : v[cur]) {
if(vis[e]) continue;
vis[e] = 1;
if(blue[cur]) {
white[e] = 1;
wans += 1;
}
if(white[cur]) {
blue[e] = 1;
bans += 1;
}
q.push(e);
}
}
}
cout<<bans<<'\n';
for(int i=1; i<=n; i++)
if(blue[i]) cout<<i<<' ';
cout<<'\n';
cout<<wans<<'\n';
for(int i=1; i<=n; i++)
if(white[i]) cout<<i<<' ';
}
'algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค 2671 (0) | 2024.08.02 |
---|---|
๋ฐฑ์ค 14848 (0) | 2024.08.02 |
๋ฐฑ์ค 25690 (0) | 2024.07.31 |
๋ฐฑ์ค 22953 (0) | 2024.07.30 |
๋ฐฑ์ค 30704 (0) | 2024.07.30 |