poj3099

bfs

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
using namespace std;

#define maxn 2005
#define inf 0x3f3f3f3f

struct Edge
{
int v, next;
}edge[maxn];

struct Point
{
int x, y, z;
}point[maxn];

struct Node
{
int d, v;
}q[maxn];

int n, id[maxn];
int head[maxn];
int length[maxn];
int ecount;
bool vis[maxn];

int dist(Point &a, Point &b)
{
Point c;
c.x
= a.x - b.x;
c.y
= a.y - b.y;
c.z
= a.z - b.z;
return c.x * c.x + c.y * c.y + c.z * c.z;
}

void addedge(int a, int b)
{
edge[ecount].next
= head[a];
edge[ecount].v
= b;
head[a]
= ecount++;
}

void input()
{
scanf(
"%d%d%d%d", &id[0], &point[0].x, &point[0].y, &point[0].z);
memset(head,
-1, sizeof(head));
ecount
= 0;
for (int i = 1; i < n; i++)
{
int mind = inf;
int mini;
scanf(
"%d%d%d%d", &id[i], &point[i].x, &point[i].y, &point[i].z);
for (int j = 0; j < i; j++)
{
int temp = dist(point[i], point[j]);
if (temp < mind)
{
mini
= j;
mind
= temp;
}
}
addedge(i, mini);
addedge(mini, i);
}
}

int bfs(int a)
{
int front = 0;
int rear = 1;
int ret = 0;
memset(vis,
0, sizeof(vis));
q[
0].d = 0;
q[
0].v = a;
vis[a]
= true;
while (front != rear)
{
Node temp
= q[front++];
if (front == maxn)
front
= 0;
if (temp.d > ret)
ret
= temp.d;
for (int i = head[temp.v]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if (!vis[v])
{
q[rear].v
= v;
q[rear].d
= temp.d + 1;
rear
++;
if (rear == maxn)
rear
= 0;
vis[v]
= true;
}
}
}
return ret;
}

int main()
{
//freopen("t.txt", "r", stdin);
while (scanf("%d", &n), n)
{
input();
memset(length,
0, sizeof(length));
for (int i = 0; i < n; i++)
length[i]
= bfs(i);
int len = inf;
int ans1 = -1, ans2 = -1;
for (int i = 0; i < n; i++)
if (length[i] < len)
{
len
= length[i];
ans1
= i;
ans2
= -1;
}
else if (length[i] == len)
ans2
= i;
if (-1 == ans2)
printf(
"%d\n", id[ans1]);
else
{
if (id[ans1] > id[ans2])
swap(ans1, ans2);
printf(
"%d %d\n", id[ans1], id[ans2]);
}
}
return 0;
}
posted @ 2011-07-17 17:41  金海峰  阅读(229)  评论(0编辑  收藏  举报