HDU 4460 Friend Chains

题目链接:HDU 4460【Friend Chains】



思路

       哈希使得每个人都有一个对应的数字,然后用邻接表存储,然后使用BFS搜索出最长的友人链。注意每一次搜索都需要初始化vis标记数组,在每一组测试样例完成后需要将mp哈希map和邻接表ve初始化为空,否则会影响计算。注意当出现两个联通块时需要输出-1。


代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <map>
using namespace std;
const int N = 1e3 + 10;

int n, m, k, res, flag;
map<string, int> mp;
vector<int>ve[N];
bool vis[N];

struct node {
  int x, step;
};

void bfs(int x) {
  vis[x] = true;
  queue<node> q;
  q.push({x, 0});

  while (!q.empty()) {
    node start = q.front();
    q.pop();
    for (auto it : ve[start.x]) {
      if (vis[it] == true)
        continue;
      vis[it] = true;
      q.push({it, start.step + 1});
    }
    res = max(res, start.step);
  }
  for (int i = 1; i <= n; i++) {
    if (vis[i] == 0) {
      flag = 1;
      return;
    }
  }
}

int main() {
  while (cin >> n){
    mp.clear();

    if (n == 0)
      break;

    for (int i = 1; i <= n; i++) {
      ve[i].clear();
      string s;
      cin >> s;
      mp[s] = i;
    }

    cin >> m;
    for (int i = 1; i <= m; i++) {
      string start, target;
      cin >> start >> target;
      ve[mp[start]].push_back(mp[target]);
      ve[mp[target]].push_back(mp[start]);
    }
    int start = 0;
    for (int i = 1; i <= n; i++) {
      memset(vis, 0, sizeof vis);
      bfs(i);
      if (flag) break;
    }
    if (flag)
      cout << -1 << endl;
    else
      cout << res << endl;
  }
  return 0;
}
posted @ 2024-07-11 16:16  薛定谔的AC  阅读(3)  评论(0编辑  收藏  举报