#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;
}
只能过一半样例。。
并查集还是很有用的,需要理解掌握。