PTA 7-7 六度空间 (30 分)
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 1001
/*test data*/
/*
10 9
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
*/
//adjacency list + Broadth_First Search + Hierarchical control
typedef struct ArcNode{
int Vertex;
struct ArcNode *next;
}ArcNode;
typedef struct VNode{
ArcNode *FirstArc;
}VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
int Nv;
int Na;
AdjList vertices;
}ALGraph;
void CreaALGraph(ALGraph &G, int VertexNum)
{
G.Nv = VertexNum;
G.Na = 0;
for(int i = 0; i <= G.Nv; i++)
G.vertices[i].FirstArc = NULL;
}
void InsertArc(ALGraph &G, int V1, int V2)
{
ArcNode *newarc1, *newarc2;
newarc1 = (ArcNode*)malloc(sizeof(ArcNode));
newarc2 = (ArcNode*)malloc(sizeof(ArcNode));
newarc1->Vertex = V2;
newarc1->next = NULL;
newarc2->Vertex = V1;
newarc2->next = NULL;
if(G.vertices[V1].FirstArc == NULL)
G.vertices[V1].FirstArc = newarc1;
else
{
newarc1->next = G.vertices[V1].FirstArc->next;
G.vertices[V1].FirstArc->next = newarc1;
}
if(G.vertices[V2].FirstArc == NULL)
G.vertices[V2].FirstArc = newarc2;
else
{
newarc2->next = G.vertices[V2].FirstArc->next;
G.vertices[V2].FirstArc->next = newarc2;
}
}
void BuildALGraph(ALGraph &G)
{
int V, V1, V2;
scanf("%d", &V);
CreaALGraph(G, V);
scanf("%d", &G.Na);
if(G.Na != 0)
{
for(int i = 0; i < G.Na; i++)
{
scanf("%d %d", &V1, &V2);
InsertArc(G, V1, V2);
}
}
}
typedef struct QNode{
int data;
QNode *next;
}QNode, *PtrToQNode;
typedef struct {
PtrToQNode front, rear;
}Queue;
//the Queue possess the head node
void InitQueue(Queue &Q)
{
Q.front = Q.rear = (PtrToQNode)malloc(sizeof(QNode));
Q.rear->next = NULL;
}
void EnQueue(Queue &Q, int e)
{
Q.rear->next = (PtrToQNode)malloc(sizeof(QNode));
Q.rear = Q.rear->next;
Q.rear->data = e;
Q.rear->next = NULL;
}
int DeQueue(Queue &Q)
{
PtrToQNode p;
p = Q.front->next;
int e = p->data;
Q.front->next = p->next;
if(p == Q.rear)
Q.rear = Q.front;
free(p);
return e;
}
int QIsEmpty(Queue Q)
{
if(Q.front == Q.rear)
return 1;
else
return 0;
}
//six degrees of separation
int visited[MAX_VERTEX_NUM];
int SDS(ALGraph G, int V)
{
int last, tail, level, cnt;
for(int i = 0; i <= G.Nv; i++)
visited[i] = 0;
Queue Q;
InitQueue(Q);
ArcNode *p;
last = V;
tail = 0;
level = 0;
cnt = 1;
EnQueue(Q, V);
visited[V] = 1;
while(!QIsEmpty(Q))
{
V = DeQueue(Q);
ArcNode *p = G.vertices[V].FirstArc;
while(p)
{
if(visited[p->Vertex] == 0)
{
visited[p->Vertex] = 1;
EnQueue(Q, p->Vertex);
cnt++;
tail = p->Vertex;
}
p = p->next;
}
if(V == last)
{
level++;
last = tail;
}
if(level == 6)
break;
}
return cnt;
}
int main()
{
ALGraph G;
BuildALGraph(G);
int num;
for(int V = 1; V <= G.Nv; V++)
{
num = SDS(G, V);
printf("%d: %.2f%%\n", V, (num*1.0)/G.Nv*100);
}
}