Loading

CodeForces-427C Checkposts

Checkposts

\(tarjan\)

如果是 \(DAG\) 图,则只用找入度为 \(0\) 的点即可

因此考虑缩点后,找所有入度为 \(0\) 的点

最小值则为,缩点后所有入度为 \(0\) 的强连通块中,每个都拿一个代价最小的点

方案数为,在上述的强连通块,记录一下代价最小的点有多少个,全部相乘即可

因此 \(tarjan\) 缩点要维护强连通块中,代价最小的点的数量

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 3e5 + 10;
const ll inf = 1e18;
const ll mod = 1e9 + 7;
ll val[maxn];
stack<int>st;
int vis[maxn], scc[maxn], cnt_scc = 0;
int low[maxn], dfn[maxn], tp = 0;
vector<int>gra[maxn];
ll minn[maxn], cnt[maxn];

void tarjan(int now)
{
    vis[now] = 1;
    st.push(now);
    dfn[now] = low[now] = ++tp;
    for(int nex : gra[now])
    {
        if(dfn[nex] == 0)
        {
            tarjan(nex);
            low[now] = min(low[now], low[nex]);
        }
        else if(vis[nex])
            low[now] = min(low[now], low[nex]);
    }
    if(low[now] == dfn[now])
    {
        cnt_scc++;
        minn[cnt_scc] = inf;
        while(st.top() != now)
        {
            int x = st.top();
            st.pop();
            vis[x] = 0;
            scc[x] = cnt_scc;
            if(val[x] == minn[cnt_scc]) cnt[cnt_scc]++;
            else if(val[x] < minn[cnt_scc]) {cnt[cnt_scc] = 1; minn[cnt_scc] = val[x];}
        }
        st.pop();
        vis[now] = 0;
        scc[now] = cnt_scc;
        if(val[now] == minn[cnt_scc]) cnt[cnt_scc]++;
        else if(val[now] < minn[cnt_scc]) {cnt[cnt_scc] = 1; minn[cnt_scc] = val[now];}
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    for(int i=1; i<=n; i++) cin >> val[i];
    int m;
    cin >> m;
    for(int i=0; i<m; i++)
    {
        int a, b;
        cin >> a >> b;
        gra[a].push_back(b);
    }
    for(int i=1; i<=n; i++)
        if(dfn[i] == 0) tarjan(i);
    ll a = 0, b = 1;
    for(int i=1; i<=cnt_scc; i++)
    {
        a += minn[i];
        b = cnt[i] * b % mod;
    }
    cout << a << " " << b << endl;
    return 0;
}
posted @ 2022-08-12 14:21  dgsvygd  阅读(42)  评论(0编辑  收藏  举报