HDU-4460 Friend Chains 暴力

题意:问给定的一张图中,相距最远最远的两个点的距离为多少。

解法:直接对每一顶点搜索一遍即可。

代码如下:

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <string>
#include <map>
using namespace std;

int N, M;
const int INF = 0x3f3f3f3f;
map<string,int>mp;

struct Edge {
    int v, next;    
};
Edge e[20005];
int idx, head[1005];
char vis[1005];
int dis[1005];
int cur, nxt, que[1005];
int front, tail;

void insert(int a, int b) {
    e[idx].v = b, e[idx].next = head[a];
    head[a] = idx++;
}

int gao(int x) {
    memset(vis, 0, sizeof (vis));
    memset(dis, 0x3f, sizeof (dis));
    front = tail = 0;
    dis[x] = 0;
    vis[x] = 1;
    que[tail++] = x;
    while (front < tail) {
        cur = que[front++];
        for (int i = head[cur]; ~i; i = e[i].next) {
            nxt = e[i].v;
            if (!vis[nxt]) {
                vis[nxt] = 1;
                dis[nxt] = dis[cur] + 1;
                que[tail++] = nxt;
            }
        }
    }
    int Max = -1;
    for (int i = 0; i < N; ++i) {
        if (dis[i] == INF) {
            return -1;
        } else {
            Max = max(Max, dis[i]);
        }
    }
    return Max;
}

int main() {
    char str[15], str2[15];
    int a, b;
    while (scanf("%d", &N), N) {
        mp.clear();
        idx = 0;
        memset(head, 0xff, sizeof (head));
        for (int i = 0; i < N; ++i) {
            scanf("%s", str);
            mp[str] = i;
        }
        scanf("%d", &M);
        for (int i = 0; i < M; ++i) {
            scanf("%s %s", str, str2);
            a = mp[str], b = mp[str2];
            insert(a, b), insert(b, a);
        }
        int ret = -1;
        for (int i = 0; i < N; ++i) {
            int t = gao(i);
            if (t == -1) {
                break;
            } else {
                ret = max(ret, t);
            }
        }
        printf("%d\n", ret);
    }
    return 0;
} 

 

posted @ 2013-05-30 12:31  沐阳  阅读(535)  评论(0编辑  收藏  举报