#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#define MAXNAME 500
#define MAX 5000
#define INFINITY -1
typedef int elemType;
typedef struct node
{
elemType data;
struct node *next;
} Node;
typedef struct queue
{
Node *head;
Node *tail;
} Queue;
void initQueue(Queue *q)
{
q->head = NULL;
q->tail = NULL;
}
void enQueue(Queue *q, elemType e)
{
Node *p;
p = (Node *)malloc(sizeof(Queue));
if(p==NULL) exit(1);
p->data = e;
p->next = NULL;
if(q->head == NULL)
{
q->head = p;
q->tail = p;
}
else
{
q->tail->next = p;
q->tail = p;
}
}
elemType deQueue(Queue *q)
{
Node *p;
elemType temp;
if(q->head == NULL) exit(1);
temp = q->head->data;
p = q->head;
q->head = q->head->next;
if(q->head == NULL)
q->tail = NULL;
free(p);
return temp;
}
int emptyQueue(Queue *q)
{
return q->head==NULL ? 1 : 0;
}
char NameList[MAX][MAXNAME];
int NamesLength;
int G[MAX][MAX];
int P,N;
int Visit[MAX];
int erdosNums[MAX];
int exists(char *name)
{
int i;
for(i=0; i<NamesLength; i++)
if(!strcmp(name,NameList[i]))
return i;
return -1;
}
void erdos()
{
int i, j;
int temp;
memset(Visit,0,sizeof(Visit));
memset(erdosNums,INFINITY,sizeof(erdosNums));
Queue q;
initQueue(&q);
enQueue(&q,0);
erdosNums[0] = 0;
while(!emptyQueue(&q))
{
temp = deQueue(&q);
Visit[temp] = 1;
for(i=0; i<NamesLength; i++)
{
if(!Visit[i] && G[temp][i])
{
if(erdosNums[i]==INFINITY || erdosNums[i]>erdosNums[temp]+1)
erdosNums[i] = erdosNums[temp]+1;
enQueue(&q,i);
}
}
}
}
int main()
{
int scenario,n;
int i,j,k,length,pos,l;
char temp[MAXNAME];
char buf[MAX];
int authors[MAX];
scanf("%d",&scenario);
for(n = 1; n <= scenario; n++)
{
scanf("%d %d\n",&P,&N);
memset(NameList,'\0',sizeof(NameList));
memset(G,0,sizeof(G));
strcpy(NameList[0],"Erdos, P.");
NamesLength = 1;
temp[0] = '\0';
for(i=0; i<P; i++)
{
gets(buf);
length = strlen(buf);
memset(authors,-1,sizeof(authors));
for(j=0,k=0,l=0; j<length; j++)
{
if(k!=0 || buf[j]!=' ')
temp[k++] = buf[j];
if(( j-1 > 0 && buf[j] == ',' && buf[j-1] == '.' ) || buf[j] == ':')
{
k--;
temp[k] = '\0';
pos = exists(temp);
if(pos==-1)
{
strcpy(NameList[NamesLength],temp);
authors[l] = NamesLength;
NamesLength++;
}
else authors[l] = pos;
l++;
k = 0;
if(buf[j]==':') break;
}
}
for(k=0; k<l; k++)
for(j=k+1; j<l; j++)
G[authors[k]][authors[j]] = G[authors[j]][authors[k]] = 1;
}
erdos();
printf("Scenario %d\n", n);
for(i=0; i<N; i++)
{
gets(temp);
for(j=0; j<NamesLength; j++)
if(!strcmp(temp,NameList[j]))
break;
printf("%s ", temp);
if(j!=NamesLength && erdosNums[j]!=INFINITY)
printf("%d\n", erdosNums[j]);
else
printf("%s\n", "infinity");
}
}
return 0;
}
UVa 10044 Erdos Numbers
最新推荐文章于 2020-07-23 10:14:22 发布