ZOJ 2913 BFS

来源:互联网 发布:javascript二维数组 编辑:程序博客网 时间:2024/06/10 05:16

需要求最短路,所以依旧是广搜

#include <cstdio>#include <iostream>#include <queue>#include <cstring>using namespace std;#define LEN 10000#define INF 100000int mz[LEN];int n, m;int edge[LEN][10];int res[LEN];int reach[LEN];int cur;int _max(int a, int b) {return a > b ? a : b;}void bfs(int s) {queue<int> que[2];int val, at;int a, b;val = 0;a = 0;b = 1;if(reach[s] < cur) {que[b].push(s);reach[s] = cur;res[s] = _max(res[s], val+1);}while(!que[b].empty()) {swap(a, b);val++;while(!que[a].empty()) {at = que[a].front();que[a].pop();for(int i = 0; i < mz[at]; i++) {if(reach[edge[at][i]] < cur) {que[b].push(edge[at][i]);reach[edge[at][i]] = cur;res[edge[at][i]] = _max(res[edge[at][i]], val+1);}}}}}int main() {int t;scanf("%d", &t);while(t--) {int id;scanf("%d%d", &n, &m);memset(reach, -1, sizeof(reach));memset(res, 0, sizeof(res));cur = 0;for(int i = 0; i < n; i++) {scanf("%d", &id);scanf("%d", &mz[id]);for(int k = 0; k < mz[id]; k++) {scanf("%d", &edge[id][k]);}}for(int i = 0; i < m; i++) {int tmp;scanf("%d", &tmp);for(int j = 0; j < tmp; j++) {scanf("%d", &id);bfs(id);cur++;}}int ret = INF;int center = -1;for(int i = 0; i < LEN; i++) {if(reach[i] == cur-1 && res[i] < ret) {ret = res[i];center = i;}}printf("%d %d\n", ret, center);}return 0;}


原创粉丝点击