상세 컨텐츠

본문 제목

부서 배치 (JUNGOL 2504)

PS,CP

by 코딩생활 2026. 5. 27. 16:00

본문

https://jungol.co.kr/problem/2504


아이디어

모든 컴포넌트에 대하여 그 컴포넌트가 이분그래프인지 확인하고, 이분그래프일때 두 종류의 정점으로 나누고 정점의 개수의 차이를 구하는 모든 과정은 O(N)에 처리가 가능합니다. 만약 모든 컴포넌트가 이분그래프라면, 각 컴포넌트마다 개수의 차이가 생길 것입니다. 이러한 컴포넌트가 K개 존재한다고 해봅시다. dp[i][j]를 i번째 컴포넌트까지 봤을 때 두 종류의 정점의 개수의 차이가 j인것이 가능한가?의 여부로 정의합시다. 이 DP테이블은 O(N2)에 구할 수 있고, 문제를 시간내에 해결할 수 있습니다. 물론 DP테이블이 크므로 두개의 dp[j]를 돌려가면서 사용해야합니다.


소스코드

#include <iostream>
#include <vector>
#include <algorithm>
#define ll long long
using namespace std;

vector <pair <ll,ll> > Graph[10101];
ll visit[10101]={0};

ll DFS(ll node,ll now)
{
    if (visit[node])
    {
        if (visit[node]!=now) return 2e9;
        return 0;
    }
    visit[node]=now;

    ll res=now;
    for (auto temp:Graph[node])
    {
        ll next=now;
        if (temp.second==-1) next=-now;
        res+=DFS(temp.first,next);
    }

    return res;
}
ll GetMinDiff(ll N, vector <ll> diff)
{
    bool dp[10101]={0},dp2[10101]={0};

    dp[0]=true;
    for (ll x:diff)
    {
        for (ll i=0;i<=N;i++)
            dp2[i]=dp[abs(i-x)]||dp[i+x];
        for (ll i=0;i<=N;i++)
            dp[i]=dp2[i];
    }

    for (ll i=0;i<=N;i++)
        if (dp[i])
            return i;
}

void solve()
{
    ll N,M,i,a,b,c;

    cin>>N>>M;
    for (i=1;i<=N;i++) Graph[i].clear(),visit[i]=0;
    for (i=0;i<M;i++)
    {
        cin>>a>>b>>c;
        Graph[b].push_back({c,a});
        Graph[c].push_back({b,a});
    }

    vector <ll> diff;
    for (i=1;i<=N;i++)
    {
        if (visit[i]) continue;
        ll now=DFS(i,1);

        if (now>N)
        {
            cout<<"-1\n";
            return;
        }

        diff.push_back(abs(now));
    }

    cout<<GetMinDiff(N,diff)<<"\n";
}

int main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);
    ll T=5;
    while (T--)
        solve();
}

'PS,CP' 카테고리의 다른 글

경로강화 (JUNGOL 1209)  (0) 2026.05.28
모바일(Mobile Phones) (JUNGOL 1554)  (0) 2026.05.28
상자 보관 (JUNGOL 8607)  (0) 2026.05.27
기준 (JUNGOL 9657)  (0) 2026.05.26
검열2 (JUNGOL 2842)  (0) 2026.05.26

관련글 더보기