본문 바로가기

알고리즘/알고리즘 이론, 템플릿

2-sat

#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#include <unordered_set>
#include <numeric>
#include <random>
#include <iostream>
#include <unordered_map>

#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rep1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define range(x) begin(x), end(x)
#define sz(x) (int)(x).size()
#define pb push_back

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vll;

const int INF = 2000000000;
const double pi = 3.14159265358979;
const int MOD = 100000;

void yesno(bool a)
{
	if (a)
		cout << "YES\n";
	else
		cout << "NO\n";
}

int N, M;
vector<int> arr[20002];
bool finished[20002]; 
stack<int> S;
int num = 0;
int sccN = 0;
int visited[20002]; 
int scc[20002];
bool check;
int result[20002];

int dfs(int start)
{
    visited[start] = ++num;
    S.push(start);
    int ret = visited[start];

    for (int next : arr[start])
    {
        if (!visited[next])
            ret = min(ret, dfs(next));
        else if (!finished[next])
            ret = min(ret, visited[next]);
    }

    if (ret == visited[start])
    {
        while (true)
        {
            int tmp = S.top();
            S.pop();
            scc[tmp] = sccN;
            finished[tmp] = true;
            if (tmp == start)
                break;
        }
        sccN++;
    }

    return ret;
}

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

    cin >> N >> M;

    for (int i = 0; i < M; i++)
    {
        int A, B;
        cin >> A >> B;

        A = (A < 0 ? -(A + 1) * 2 : A * 2 - 1);
        B = (B < 0 ? -(B + 1) * 2 : B * 2 - 1);

        arr[A % 2 ? A - 1 : A + 1].pb(B);
        arr[B % 2 ? B - 1 : B + 1].pb(A);
    }

    rep(i, N * 2)
    {
        if (visited[i] == 0)
            dfs(i);
    }

    for (int i = 0; i < N; i++)
    {
        if (scc[i * 2] == scc[i * 2 + 1])
        {
            check = true;
        }
    }

    if (check)
        cout << "yes" << "\n";
    else
        cout << "no" << "\n";

	
	return 0;
}

'알고리즘 > 알고리즘 이론, 템플릿' 카테고리의 다른 글

Atcoder ACL  (0) 2024.11.13
mcmf  (0) 2024.03.07
네트워크 플로우  (0) 2024.03.07
머지소트트리  (0) 2024.03.03
LCA , sparsetable  (0) 2023.12.11