CodeForces-505D Kitayuta先生的技术

分类:编程技术 时间:2024-02-20 17:48 浏览:0 评论:0
0

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

Mr. Kitayuta's Technology

tarjan + 思维

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

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

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

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

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

#include #include #include #include #include #include using namespace std;const int maxn = 1e5 + 10;vectorgra[maxn], gra_c[maxn];stackst;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;}


1. 本站所有资源来源于用户上传或网络,仅作为参考研究使用,如有侵权请邮件联系站长!
2. 本站积分货币获取途径以及用途的解读,想在本站混的好,请务必认真阅读!
3. 本站强烈打击盗版/破解等有损他人权益和违法作为,请各位会员支持正版!
4. 编程技术 > CodeForces-505D Kitayuta先生的技术

用户评论