仍然是宽搜,但这是分层宽搜,类似第三届新手赛网络预选赛的第二题,注意层数的标记即可,另外要注意这是无向图。
Run Time: 0.01sec
Run Memory: 1164KB
Code length: 1044Bytes
Submit Time: 2011-12-24 11:57:04
// Problem#: 4376
// Submission#: 1120883
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int main()
{
int n, m;
int i, j;
queue<int> q;
int count, dist;
int shortest[ 1001 ];
bool path[ 1001 ][ 1001 ];
memset( shortest, -1, sizeof( shortest ) );
memset( path, false, sizeof( path ) );
scanf( "%d%d", &n, &m );
while ( m-- ) {
scanf( "%d%d", &i, &j );
path[ i ][ j ] = true;
path[ j ][ i ] = true;
}
dist = 0;
q.push( 1 );
shortest[ 1 ] = dist;
while ( !q.empty() ) {
count = q.size();
dist++;
while ( count-- ) {
i = q.front();
for ( j = 1; j <= n; j++ ) {
if ( path[ i ][ j ] && shortest[ j ] == - 1 ) {
q.push( j );
shortest[ j ] = dist;
}
}
q.pop();
}
}
for ( i = 1; i <= n; i++ )
printf( "%d ", shortest[ i ] );
printf( "\n" );
return 0;
}