Sicily 4376. shortest path in unweighted graph

仍然是宽搜,但这是分层宽搜,类似第三届新手赛网络预选赛的第二题,注意层数的标记即可,另外要注意这是无向图。

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;

}                                 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值