(自用随笔)PAT A1034 Head of a Gang

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int N,K;
int father[2005];
int isRoot[2005] = {0};
int sum[2005] = {0};
int numb = 0;
int gun[2005] = {0};

typedef struct relat
{
    int from,to;
} trela;

trela *rela;

typedef struct node
{
    char name[4];
    int num;
    int time;
} tNode;

tNode *Node;

int findfather(int x)
{
    int a = x;
    while(x != father[x])
    {
        x = father[x];
    }

    while(a != father[a])
    {
        int z = a;
        a = father[a];
        father[z] = x;
    }
    return x;
}

void Union(int a,int b)
{
    int faA = findfather(a);
    int faB = findfather(b);
    if(faA != faB)
    {
        if(Node[faA].time>Node[faB].time)
        {
            father[faB] = faA;
        }
        else
        {
            father[faA] = faB;
        }
    }
}

int cmp(const void* _a,const void* _b)
{
    int *a = (int*)_a;
    int *b = (int*)_b;
    return strcmp(Node[*a].name,Node[*b].name);
}

int main()
{
    rela = (trela*)malloc(2005*sizeof(trela));
    Node = (tNode*)malloc(2005*sizeof(tNode));
    char str1[4],str2[4];
    int temp;
    scanf("%d %d",&N,&K);
    int person = 0;
    for(int i = 0; i<N*2+1; i++)
    {
        father[i] = i;
    }
    for(int i = 0; i<N; i++)
    {
        scanf("%s %s %d",str1,str2,&temp);
        int m;
        for(m = 0; m<person; m++)
        {
            if(strcmp(str1,Node[m].name) == 0)
            {
                Node[m].time+=temp;
                break;
            }
        }
        if(m == person)
        {
            strcpy(Node[m].name,str1);
            Node[m].time+=temp;
            person++;
        }

        int n;
        for(n = 0; n<person; n++)
        {
            if(strcmp(str2,Node[n].name) == 0)
            {
                Node[n].time+=temp;
                break;
            }
        }
        if(n == person)
        {
            strcpy(Node[n].name,str2);
            Node[n].time+=temp;
            person++;
        }

        rela[i].from = m;
        rela[i].to = n;

    }

    for(int q = 0;q<person;q++)
    {
        Union(rela[q].from,rela[q].to);
    }

    for(int j = 0; j<person; j++)
    {
        isRoot[findfather(j)]++;
        sum[findfather(j)] += Node[j].time;
    }

    for(int k = 0; k<person; k++)
    {
        if(isRoot[k]>=3)
        {
            gun[numb++] = k;
        }
    }
    printf("%d\n",numb);
    qsort(gun,numb,sizeof(int),cmp);

    for(int l = 0; l<numb; l++)
    {
        printf("%s %d\n",Node[gun[l]].name,isRoot[gun[l]]);
    }
    return 0;
}

只能过一半样例。。

并查集还是很有用的,需要理解掌握。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值