CodeForces-505D Mr. Kitayuta's Technology

2022/8/25 6:24:16

本文主要是介绍CodeForces-505D Mr. Kitayuta's Technology,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Mr. Kitayuta's Technology

tarjan + 思维

先缩点,然后考虑如何建边

如果其中一个 \(DAG\) 图中出现一个缩点后大小大于 \(2\) 的连通块(环),则考虑直接将这个 \(DAG\) 图变成一个环,代价显然都是相同的,即点的数量

因此延伸,考虑多个缩点前都有环的 \(DAG\) 图,我们不妨将他们全部变成一个大的环,这样的代价即为所有的点的数量

如果原图即为 \(DAG\) 图,则代价就是点的数量 \(-1\),参考树的结构

因此直接用并查集维护缩点后的 \(DAG\) 图,判断一下 \(-1\) 的情况即可

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
const int maxn = 1e5 + 10;
vector<int>gra[maxn], gra_c[maxn];
stack<int>st;
int vis[maxn], scc[maxn], scc_cnt = 0;
int dfn[maxn], low[maxn], tp = 0;
int siz[maxn], in[maxn], fa[maxn];
int rnd[maxn];

void tarjan(int now)
{
    dfn[now] = low[now] = ++tp;
    st.push(now);
    vis[now] = 1;
    for(int nex : gra[now])
    {
        if(dfn[nex] == 0)
        {
            tarjan(nex);
            low[now] = min(low[now], low[nex]);
        }
        else if(vis[nex] == 1)
            low[now] = min(low[now], low[nex]);
    }
    if(dfn[now] == low[now])
    {
        scc_cnt++;
        int top;
        do
        {
            top = st.top();
            st.pop();
            vis[top] = 0;
            siz[scc_cnt]++;
            scc[top] = scc_cnt;
        }while(top != now);
    }
}

int query(int x)
{
    return x == fa[x] ? x : fa[x] = query(fa[x]);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, m;
    cin >> n >> m;
    while(m--)
    {
        int a, b;
        cin >> a >> b;
        gra[a].push_back(b);
    }
    for(int i=1; i<=n; i++)
        if(dfn[i] == 0) tarjan(i);
    int ans = n;
    for(int i=1; i<=scc_cnt; i++)
    {
        fa[i] = i;
        rnd[i] = siz[i] > 1;
    }
    for(int i=1; i<=n; i++)
    {
        for(int nex : gra[i])
        {
            if(scc[i] != scc[nex])
            {
                int aa = query(scc[i]), bb = query(scc[nex]);
                if(aa != bb)
                {
                    fa[aa] = bb;
                    rnd[bb] |= rnd[aa];
                }
            }
        }
    }
    for(int i=1; i<=scc_cnt; i++) if(fa[i] == i && rnd[i] == 0) ans--;
    cout << ans << endl;
    return 0;
}


这篇关于CodeForces-505D Mr. Kitayuta's Technology的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程