PTA_2021年团体程序设计天梯赛_总决赛_L2-2 病毒溯源 (25 分)

//
输入样例:
10
3 6 4 8
0
0
0
2 5 9
0
1 7
1 2
0
2 3 1
输出样例:
4
0 4 9 1

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

const int N=1e4+5;
bool judge[N];
int t[N],ans[N];
int len;
vector<int> v[N];

bool is_small( int *a,int *b,int n )
{
    for( int i=0;i<n;++i )
    {
        if( a[i]==b[i] ) continue;
        else if( a[i]<b[i] ) return true;
        else if( a[i]>b[i] ) return false;
    }
    return false;   // 全等
}

void dfs( int x,int cnt )
{
    int i;
    if( v[x][0]==0 )
    {
        if( cnt>len || cnt==len && is_small( t,ans,cnt ) )
        {
            len=cnt;                            // 更新
            for( i=0;i<cnt;++i ) ans[i]=t[i];
        }
        return ;
    }
    for( i=1;i<=v[x][0];++i )
    {
        t[cnt]=v[x][i];
        dfs( v[x][i],cnt+1 );
    }
}

void init()
{
    memset( judge,0,sizeof( judge ) );
    memset( t,0,sizeof( t ) );
    memset( ans,0,sizeof( ans ) );
    for( int i=0;i<N;++i ) v[i].clear();
    len=0;
}

int main()
{
	int n,i,k,x;
	
    while( cin>>n )
    {
        init();
        for( i=0;i<n;++i )
        {
            cin>>k; if( k==0 ) judge[i]=1;		// i

            v[i].push_back( k );
            while( k-- )
            {
                cin>>x;
                judge[x]=1;
                v[i].push_back( x );
            }
        }
        for( i=0;i<n;++i ) 				// 输出从源头开始最长变异链 !!!
            if( judge[i]==0 ) break;
            
        if( n==1 ) { cout<<1<<endl<<0<<endl; continue; }	// 处理特殊数据 

        t[0]=i; dfs( i,1 );

        cout<<len<<endl;
        for( i=0;i<len;++i )
        {
            if(i) cout<<' ';
            cout<<ans[i];
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

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