Beehives
.
.
题意:给出一个无向图,求最短的环
.
.
解法:由于点数只有500, 对于每一个点做一次bfs就好了,只要搜到之前更新过的点那么就是一个环了,bfs保证了最短。
.
.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn = 600;
const int INF = 1000000;
const int maxm = 21000;
int dist[maxn], n, m, d[maxn], x, y, ans, pre[maxn];
int tar[2*maxm], nextt[2*maxm], last[maxn], tot;
template <typename T>
inline bool scan_d(T &ret) {
char c; int sgn;
if (c = getchar(), c == EOF) return 0;
while (c != '-' && (c < '0' || c > '9')) c = getchar();
sgn = (c == '-')?-1:1;
ret = (c == '-')?0:(c-'0');
while (c = getchar(), c >= '0' && c <= '9') ret = ret*10+(c-'0');
ret *= sgn;
return 1;
}
void insert(int x, int y) {
tot++;
tar[tot] = y;
nextt[tot] = last[x];
last[x] = tot;
}
int bfs(int s) {
memset(dist, 255, sizeof(dist));
memset(pre, 0, sizeof(pre));
dist[s] = 0;
int i = 0, j = 1;
d[1] = s;
int minn = INF;
while (i != j) {
i++;
if (i > INF) i = 1;
int k = last[d[i]];
while (k != 0) {
if (dist[tar[k]] == -1) {
dist[tar[k]] = dist[d[i]]+1;
pre[tar[k]] = d[i];
j++;
if (j > INF) j = 1;
d[j] = tar[k];
} else if (tar[k] != pre[d[i]]) {
minn = min(minn, dist[tar[k]]+dist[d[i]]+1);
}
k = nextt[k];
}
}
return minn;
}
int main() {
int tt;
scanf("%d", &tt);
for (int cases = 1; cases <= tt; cases++) {
tot = 0;
memset(last, 0, sizeof(last));
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
scan_d(x);
scan_d(y);
x++; y++;
insert(x, y);
insert(y, x);
}
ans = INF;
for (int i = 1; i <= n; i++) {
ans = min(ans, bfs(i));
}
printf("Case %d: ", cases);
if (ans == INF) printf("impossible\n");
else printf("%d\n", ans);
}
}