- 문제 링크 : boj.kr/3295
- 난이도 : P2
- 태그 : 최대 유량
코드
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define INF 0x7FFFFFFF
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll, ll>;
class Flow {
vector<vector<int>> edge;
vector<vector<int>> f, c;
int n;
public:
Flow(int n) {
this->n = n;
edge.resize(n);
f = vector<vector<int>>(n, vector<int>(n));
c = vector<vector<int>>(n, vector<int>(n));
}
int flow(int start, int end) {
init();
int ans = 0;
while(true) {
//BFS
vector<int> parent(n, -1);
queue<int> _q;
parent[start] = start;
_q.push(start);
while(!_q.empty() && parent[end] == -1) {
int curr = _q.front(); _q.pop();
for(auto u : edge[curr]) {
if(c[curr][u] - f[curr][u] > 0 && parent[u] == -1) {
_q.push(u);
parent[u] = curr;
if(u == end) break;
}
}
}
if(parent[end] == -1) break;
//check amount
int amount = INF;
int curr = end;
while(curr != start) {
int before = parent[curr];
amount = min(amount, c[before][curr] - f[before][curr]);
curr = before;
}
//set
curr = end;
while(curr != start) {
int before = parent[curr];
f[before][curr] += amount;
f[curr][before] -= amount;
curr = before;
}
ans += amount;
}
return ans;
}
void add_edge(int x, int y, int c, bool b = 0) {
edge[x].push_back(y);
edge[y].push_back(x);
this->c[x][y] = c;
if(b) this->c[x][y] = c; //양방향 그래프
}
private:
void init() {
for(auto &u : f) {
for(auto &v : u) {
v = 0;
}
}
}
};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int T;
cin >> T;
while(T--) {
int n, m;
cin >> n >> m;
int S = 2*n + 2;
Flow f(S);
for(int i = 0; i < n; i++) {
f.add_edge(0, i+1, 1);
f.add_edge(i+1 + n, S-1, 1);
}
for(int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
f.add_edge(u+1, v+1 + n, 1);
}
cout << f.flow(0, S-1) << "\n";
}
return 0;
}
풀이
문제에서 요구하는 상태는 모든 노드가 나가는 간선이 1개 이하, 들어오는 간선이 1개 이하인 상태를 말한다.
단방향 링크를 두 노드로 나누어 최대 유량을 구해주면 된다.
728x90
'PS' 카테고리의 다른 글
BOJ 1214 : 쿨한 물건 구매 (0) | 2024.11.14 |
---|---|
BOJ 16903 : 수열과 쿼리 20 (0) | 2024.11.13 |
BOJ 3683 : 고양이와 개 (0) | 2024.11.12 |
BOJ 1671 : 상어의 저녁식사 (0) | 2024.11.11 |
BOJ 11375 : 열혈강호 (1) | 2024.11.10 |