标签:des style blog http io ar color os sp
题目大意:给你一个朋友之间的关系让你判断所有人之间的朋友“链”的最大长度,如果大于7就不可以,否则输出最大值。
枚举n个点进行n次spfa。
3 XXX YYY ZZZ 2 XXX YYY YYY ZZZ 0
2
#include <algorithm> #include <iostream> #include <stdlib.h> #include <string.h> #include <iomanip> #include <stdio.h> #include <string> #include <queue> #include <cmath> #include <time.h> #include <stack> #include <map> #include <set> #define eps 1e-8 ///#define LL long long #define LL __int64 #define INF 0x3f3f3f #define PI 3.1415926535898 #define mod 1000000007 using namespace std; const int maxn = 1010; map<string, int> mp; string str; string str1; struct node { int v; int w; int next; }f[maxn*maxn/2]; int head[maxn*maxn/2]; int cnt; void init() { cnt = 0; memset(head, -1, sizeof(head)); } void add(int u, int v, int w) { f[cnt].v = v; f[cnt].w = w; f[cnt].next = head[u]; head[u] = cnt++; f[cnt].v = u; f[cnt].w = w; f[cnt].next = head[v]; head[v] = cnt++; } int spfa(int x, int n) { bool vis[maxn]; int dis[maxn]; queue<int>que; for(int i = 1; i <= n; i++) { dis[i] = INF; vis[i] = false; } dis[x] = 0; vis[x] = true; que.push(x); while(!que.empty()) { int sx = que.front(); que.pop(); vis[sx] = false; for(int i = head[sx]; i != -1; i = f[i].next) { int v = f[i].v; if(dis[v] > dis[sx]+f[i].w) { dis[v] = dis[sx]+f[i].w; if(!vis[v]) { vis[v] = true; que.push(v); } } } } int Max = 0; for(int i = 1; i <= n; i++) { if(!dis[i]) continue; Max = max(Max, dis[i]); } return Max; } vector<int>g[maxn]; bool sta[maxn]; void dfs(int x, int fa) { sta[x] = 1; for(int i = head[x]; i != -1; i = f[i].next) { int sx = f[i].v; if(sta[sx] || sx == fa) continue; dfs(sx, x); } } int main() { int n; while(~scanf("%d",&n) && n) { for(int i = 1; i <= n; i++) { cin >>str; mp[str] = i; } int m; scanf("%d",&m); int x, y; init(); for(int i = 0; i < m; i++) { cin >>str>>str1; x = mp[str]; y = mp[str1]; add(x, y, 1); } memset(sta, false, sizeof(sta)); dfs(1, -1); int xflag = 0; for(int i = 1; i <= n; i++) { if(sta[i]) continue; xflag = 1; break; } if(xflag) { puts("-1"); continue; } int flag = 0; int Max = 0; for(int i = 1; i <= n; i++) { int sx = spfa(i, n); if(sx >= 7) { flag = 1; break; } Max = max(Max, sx); } if(flag) { puts("-1"); continue; } printf("%d\n",Max); } }
HDU 4460 Friend Chains(map + spfa)
标签:des style blog http io ar color os sp
原文地址:http://blog.csdn.net/xu12110501127/article/details/41592819