poj 2021 Relative Relatives(暴力)

题目链接:http://poj.org/problem?id=2021

思路分析:由于数据较小,采用O(N^2)的暴力算法,算出所有后代的年龄,再排序输出。

 

代码分析:

#include <iostream>
#include <string.h>
#include <algorithm>

using namespace std;
#define MAX_N ( 100 + 10 )

typedef struct Descendant
{
    char Name[30];
    int Age;
}Desd;

char Father[MAX_N][30];
char Child[MAX_N][30];
int Age[MAX_N];
Desd Descen[MAX_N];
int Cmp( Desd a, Desd b );

int main()
{
    int n, Count;

    Count = 0;
    strcpy( Descen[0].Name, "Ted" );
    Descen[0].Age = 100;

    scanf( "%d", &n );
    for ( int i = 0; i < n; ++i )
    {
        int Num, Index_Father, EndDescen;

        Index_Father = EndDescen = 0;
        Count++;

        scanf( "%d\n", &Num );
        for ( int j = 0; j < Num; ++j )
            scanf( "%s %s %d", Father[j], Child[j], &Age[j] );

        while ( Index_Father < Num )
        {
            for ( int m = 0; m < Num; ++m )
            {
                if ( strcmp( Descen[Index_Father].Name, Father[m] ) == 0 )
                {
                    EndDescen++;
                    strcpy( Descen[EndDescen].Name, Child[m] );
                    Descen[EndDescen].Age = Descen[Index_Father].Age - Age[m];
                }
            }
            Index_Father++;
        }

        sort( Descen, Descen + Num + 1, Cmp );

        printf( "DATASET %d\n", Count );
        for ( int n = 1; n <= Num; ++n )
            printf( "%s %d\n", Descen[n].Name, Descen[n].Age );
    }

    return 0;
}

int Cmp( Desd a, Desd b )
{
    if ( a.Age == b.Age )
        return strcmp( a.Name, b.Name ) < 0;
    else
        return a.Age > b.Age;
}

 

你可能感兴趣的:(relative)