WOJ1006 - Language of Animals

According to Ernest Mayr, America's leading taxonomist, there are over 1 million species of animals in the world.When all
kinds of animals took boat,they found a problem.Each kind of animal had its own language,so the communication became
very hard.Assume that animal A could communicate with animal B but it couldn't communicate with animal C,while animal C
could only communicate with animal B. So,animal B must translate what one said to the other if animal A and animal C wanted
to communicate with each other.We called animal B translator.Noah wanted to know the least translators if two animals
wanted to communicate with each other.

输入格式

There will be only one test case.The first line contains two integers n(2 <= n <=200,000) and
m(1 <= m <= 300,000),where n represents the number of animals and m represents the number of pairs which could
communicate with each other. The next m lines contains two numbers each,representing two animals who can communicate
with each other. The number starts at 0.The next line contains a integer k(k<=20) representing the number of queries,and
the last k lines contains two number each,representing two animals who wanted to communicate with each other.

输出格式

For each query,you should output the least translators if two animals in that query wanted to communicate with each other.
If they couldn't communicate with each other by translating ,output "-1".

样例输入

3 2
0 1
1 2
2
0 0
0 2

样例输出

0
1

对k个询问每个用spfa做一次就OK了

STL vector用法介绍

学习SPFA:

http://www.360doc.com/content/13/1208/22/14357424_335569176.shtml

http://baike.baidu.com/link?url=P06iyRkNxxdnYofqhZPAO-b5ttALUlBfVwA23mQTKAD0dXB1KTWdRvsoPNaM43HoTpmdIc04KVZFp1IIzriLhS4dNJxwyizyz4cZvuFLGFMGrmHgDUdeDPi1S22TjbrZ5XlsB_EHYvBJWAIi8OQLTa

#include 
#include 
#include 
#include 
#include 
using namespace std;
int n,m,k,dist[200002];
vector g[200002];

inline bool relax(int u,int v)
{
    if(dist[u]+1 q;
    q.push(s);
    vis[s] = true;
    dist[s] = 0;
    while(!q.empty())
    {
        int temp=q.front();
        q.pop();
        for(int i=0;i

类似的bfs解法:

点击打开链接


你可能感兴趣的:(WOJ)