woj 1006 Language of Animals

不要被数据范围吓到……

链表+简单的bfs。不喜欢用链表所以写了vector。

/*
 * Author: stormdpzh
 * Created Time: 2012/7/11 22:19:27
 * File Name: woj_1006.cpp
 */
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define sz(v) ((int)(v).size())
#define rep(i, n) for(int i = 0; i < n; i++)
#define repf(i, a, b) for(int i = a; i <= b; i++)
#define repd(i, a, b) for(int i = a; i >= b; i--)
#define out(n) printf("%d\n", n)
#define mset(a, b) memset(a, b, sizeof(a))
#define wh(n) while(1 == scanf("%d", &n))
#define whz(n) while(1 == scanf("%d", &n) && n != 0)
#define lint long long

using namespace std;

const int MaxN = 200005;

vector vec[MaxN];
bool visited[MaxN];
int n, m, k;
struct Node {
    int a, l;
    Node(int _a, int _l) : a(_a), l(_l) {}
};

void init()
{
    rep(i, n) vec[i].clear();
    rep(i, m) {
        int a, b;
        scanf("%d%d", &a, &b);
        vec[a].push_back(b);
        vec[b].push_back(a);
    }
    scanf("%d", &k);
}

int gao(int s, int e)
{
    mset(visited, false);
    visited[s] = true;
    queue que;
    que.push(Node(s, 0));
    while(!que.empty()) {
        Node tmp = que.front();
        que.pop();
        if(tmp.a == e) {
            if(tmp.l >= 1) return tmp.l - 1;
            return tmp.l;
        }
        for(vector::iterator it = vec[tmp.a].begin(); it != vec[tmp.a].end(); it++) {
            if(!visited[*it]) {
                visited[*it] = true;
                que.push(Node(*it, tmp.l + 1));
            }
        }
    }
    return -1;
}

int main()
{
    while(2 == scanf("%d%d", &n, &m)) {
        init();
        rep(i, k) {
            int a, b;
            scanf("%d%d", &a, &b);
            out(gao(a, b));
        }
    }    
    return 0;
}


你可能感兴趣的:(woj)