L2-038 病毒溯源(团体程序设计天梯赛-练习集)

link

此题有坑,需要找到病毒源头,0并不一定是

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100010;

int h[MAXN], e[MAXN], ne[MAXN], idx;
int st[MAXN], p[MAXN], dis[MAXN];
int yuantou, ed, maxv = 1;
int n;

bool cmp(int a, int b){
    return a > b;
}

void add(int a, int b){
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void bfs(){
    memset(dis, -1, sizeof dis);
    queue<int> q;
    q.push(yuantou);
    dis[yuantou] = 1;

    while(q.size()){
        int t = q.front();
        q.pop();
        for(int i = h[t]; i != -1; i = ne[i]){
            int j = e[i];
            dis[j] = dis[t] + 1;
            if(maxv < dis[j]){
                maxv = dis[j];
                ed = j;
            }
            q.push(j);
        }
    }
    return ;
}
void print(int x){
    if(x == yuantou){
        cout << x;
        return ;
    }
    print(p[x]);
    printf(" %d", x);
}

int main(){
    memset(h, -1, sizeof h);
    scanf("%d", &n);

    for(int i = 0; i < n; i++){
        int k;
        cin >> k;
        int b[k];
        for(int j = 0; j < k; j++) cin >> b[j];
        sort(b, b + k, cmp);
        for(int j = 0; j < k; j++){
            st[b[j]] = 1;
            p[b[j]] = i;
            add(i, b[j]);
        }
    }

    for(int i = 0; i < n; i++) if(!st[i]) yuantou = i;

    bfs();

    cout << maxv << endl;

    print(ed);
    
    return 0;
}
posted @ 2025-03-07 17:44  awei040519  阅读(22)  评论(0)    收藏  举报