#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
#define L 1003
using namespace std;
int P, D;
vector <int> node[L];
int check1[L][L];
int visited[L][L], ans[L];
void BFS(){
queue <int> tracking;
tracking.push(0);
ans[0] = 0;
int Z;
while(!tracking.empty()){
int u = tracking.front();
int sz = node[u].size();
for(int i = 0; i < sz; i++){
int v = node[u][i];
if(!visited[u][v] && !visited[v][u]){
visited[u][v] = 1, visited[v][u] = 1;
tracking.push(v);
if(ans[v] == -1)ans[v] = ans[u]+1;
}
}
tracking.pop();
}
}
int main(){
int t, x, y;
cin >> t;
while(t--){
memset(check1, 0, sizeof(check1));
memset(visited, 0, sizeof(visited));
memset(ans, -1, sizeof(ans));
cin >> P >> D;
for(int i = 1; i <= D; i++){
cin >> x >> y;
if(check1[x][y] || check1[y][x])continue;
check1[x][y] = 1, check1[y][x] = 1;
node[x].push_back(y);
node[y].push_back(x);
}
BFS();
for(int i = 1; i < P; i++)cout << ans[i] << endl;
if(t)cout << endl;
for(int i = 0; i < L; i++)node[i].clear();
}
return 0;
}
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
#define L 1003
using namespace std;
int P, D;
vector <int> node[L];
int check1[L][L];
int visited[L][L], ans[L];
void BFS(){
queue <int> tracking;
tracking.push(0);
ans[0] = 0;
int Z;
while(!tracking.empty()){
int u = tracking.front();
int sz = node[u].size();
for(int i = 0; i < sz; i++){
int v = node[u][i];
if(!visited[u][v] && !visited[v][u]){
visited[u][v] = 1, visited[v][u] = 1;
tracking.push(v);
if(ans[v] == -1)ans[v] = ans[u]+1;
}
}
tracking.pop();
}
}
int main(){
int t, x, y;
cin >> t;
while(t--){
memset(check1, 0, sizeof(check1));
memset(visited, 0, sizeof(visited));
memset(ans, -1, sizeof(ans));
cin >> P >> D;
for(int i = 1; i <= D; i++){
cin >> x >> y;
if(check1[x][y] || check1[y][x])continue;
check1[x][y] = 1, check1[y][x] = 1;
node[x].push_back(y);
node[y].push_back(x);
}
BFS();
for(int i = 1; i < P; i++)cout << ans[i] << endl;
if(t)cout << endl;
for(int i = 0; i < L; i++)node[i].clear();
}
return 0;
}
No comments:
Post a Comment