2019CCPC-Harbin E(拓撲排序)

 Note:T很大,初始化就容易超時。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,ll> piir;
const int maxn = 1e6+5;

vector<int> s[maxn];
vector<int> G[maxn];
unordered_map<int,ll> ans;
queue<piir> qp;
int in[maxn];
ll num[maxn];
int n;
void init(){
    for(int i=0;i<=n;i++){
        num[i]=0;
        in[i]=0;
        s[i].clear();
        G[i].clear();
    }
    while(!qp.empty()) qp.pop();
    ans.clear();
}
int main(){
#ifndef  ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int t;
    scanf("%d",&t);
    while(t--){
        ll tot=0;
        scanf("%d",&n);
        init();
        for(int i=1;i<=n;i++){
            int op,k,x,y;
            scanf("%d",&op);
            if(op==1){
                int num;
                scanf("%d",&k);

                for(int j=1;j<=k;j++){
                    scanf("%d",&num);
                    s[i].push_back(num);
                }
            }
            else {
                scanf("%d%d",&x,&y);
                G[i].push_back(x);
                G[i].push_back(y);
                in[x]++;
                in[y]++;
            }
        }
        int u;
        for(int i=1;i<n;i++) if(in[i]==0) qp.push(piir(i,0));
        qp.push(piir(n,0));
        num[n] = 1;
        ll cnt=0;
        while(!qp.empty())
        {
            u=qp.front().first;
            qp.pop();
            for(auto v:G[u]){
                in[v]--;
                num[v] += num[u];
                if(!in[v]) qp.push(piir(v,0));
            }
        }

        ll mx = -1;
        for(int i=1;i<=n;i++){
//            cout<<i<<' '<<num[i]<<' '<<endl;
            if(num[i] && G[i].size()==0) {
                tot+=1ll*s[i].size()*num[i];
                for(auto it:s[i]) {
                    ans[it]+=num[i];

                    mx = max(mx,ans[it]);
                }
            }
        }
        if(mx <= (tot-mx)) printf("%lld\n",tot);
        else printf("%lld\n",2*(tot-mx));
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章