PTA_2021年总决赛_L2-2 病毒溯源 (25 分)_dfs

// L2-2 病毒溯源 (25 分)
#include<bits/stdc++.h>
using namespace std;

const int N=1e4+5;
vector<int> vv[N];
bool used[N];
int ans[N],tt[N];
int anslen=0;

bool f( int len )
{
    for( int i=0;i<len;i++ )
    {
        if( ans[i]==tt[i] ) continue;
        else if( ans[i]<tt[i] ) return false;
        else if( ans[i]>tt[i] ) return true;
    }
    return true;    // 如果最长链不唯一,则输出最小序列
}

void dfs( int pos,int len )
{
    int i;
    if( vv[pos][0]==0 )
    {
        if( len>anslen || len==anslen && f(len) ) 
        {
            anslen=len;            // 更新长度 
            for( i=0;i<len;i++ )
                        ans[i]=tt[i];
        }
    }
    for( i=1;i<=vv[pos][0];i++ )     // <= !!!
    {
        tt[len]=vv[pos][i];
        dfs( vv[pos][i],len+1 );
    }
}

int main()
{
    int n,i,k,x;
    
    while( cin>>n )
    {
        memset( used,0,sizeof( used ) );

        for( i=0;i<n;i++ )
        {
            cin>>k; vv[i].push_back(k);

            while( k-- )
            {
                cin>>x; used[x]=1; vv[i].push_back(x);
            }
        }
        for( i=0;i<n;i++ )			// 找病毒源 
        {
            if( used[i]==0 ) break;
        }
        tt[0]=i; dfs( i,1 );		

        cout<<anslen<<endl;
        for( i=0;i<anslen;i++ )
        {
            if( i ) cout<<" ";
            cout<<ans[i];
        }
        cout<<endl;
    }
    return 0;
}
// 首先输出从源头开始最长变异链的长度。

猜你喜欢

转载自blog.csdn.net/qq_63173957/article/details/124310264