티스토리 뷰
문제
https://www.acmicpc.net/problem/11281
알고리즘
2-SAT
풀이
이 문제에서 실제 해까지 찾아서 출력하는 문제입니다. SCC 이후 하나의 간선을 구성하는 두 정점을 살펴봅시다. 앞서 살펴본 바와 같이 u->v를 만족하기 위해선 not u 일 땐 v가 무엇이 와도 상관이 없으나 True u 일 땐 2-CNF에서의 절을 만족하기 위해 v가 True임이 강제됩니다. 즉 우리는 위상 정렬상 빠른 쪽에 위치한 정점을 False로 평가하는 것이 True로 평가하는 것에 비해 항상 이득임을 알 수 있습니다.
코드
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;++i)
#define REP(i,n) for(int i=1;i<=n;++i)
#define FAST cin.tie(NULL);cout.tie(NULL); ios::sync_with_stdio(false)
using namespace std;
#define t(x) (x<<1)
#define f(x) (x<<1|1)
#define W(x) (x>0?t(x-1):f(-(x+1)))
int N, M, u, v, VC, SC;
vector<vector<int>> adj;
vector<int> discovered, sccid;
stack<int> st;
void OR(int u, int v) {
adj[W(u) ^ 1].emplace_back(W(v));
adj[W(v) ^ 1].emplace_back(W(u));
}
int scc(int here) {
int ret = discovered[here] = VC++;
st.emplace(here);
for (auto there : adj[here]) {
if (discovered[there] == -1) ret = min(ret, scc(there));
else if (sccid[there] == -1) ret = min(ret, discovered[there]);
}
if (ret == discovered[here]) {
while (1) {
int t = st.top();
st.pop();
sccid[t] = SC;
if (t == here) break;
}
++SC;
}
return ret;
}
int main() {
FAST;
cin >> N >> M;
adj.resize(N << 1);
rep(i, M) {
cin >> u >> v;
OR(u, v);
}
discovered = sccid = vector<int>(N << 1, -1);
rep(i, N << 1) if (discovered[i] == -1) scc(i);
bool flag = 1;
rep(i, N) if (sccid[t(i)] == sccid[f(i)]) {
flag = 0;
break;
}
cout << flag << '\n';
if (flag) {
rep(i, N) {
if (sccid[t(i)] < sccid[f(i)]) cout << 1 << ' ';
else cout << 0 << ' ';
}
}
return 0;
}
'Algorithm' 카테고리의 다른 글
[백준 15675] 괴도 강산 (0) | 2020.08.13 |
---|---|
[백준 3648] 아이돌 (0) | 2020.08.12 |
[백준 11280] 2-SAT -3 (0) | 2020.08.09 |
[백준 15483] 최소 편집 (0) | 2020.08.06 |
[백준 1108] 검색 엔진 (0) | 2020.08.05 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- greedy
- implementation
- spring
- string
- SCC
- Segment tree
- 펜윅트리
- bfs
- 동적계획법
- 2-SAT
- 트라이
- union find
- 스위핑
- spring boot
- DP
- dfs
- kmp
- 이분탐색
- knapsack
- 이분매칭
- hld
- sorting
- 세그먼트트리
- Suffix Array
- 정렬
- Fenwick
- sweeping
- 좌표압축
- dijkstra
- Oracle
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함