POJ3114(Countries in War)

Countries in War
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 502 Accepted: 135

Description

In the year 2050, after different attempts of the UN to maintain peace in the world, the third world war broke out. The importance of industrial, commercial and military secrets obliges all the countries to use extremely sophisticated espionage services, so that each city in the world has at least one spy of each country. These spies need to communicate with other spies, informers as well as their headquarters during their actions. Unluckily there doesn’t exist a secure way for a spy to communicate during the war period, therefore the messages are always sent in code so that only the addressee is able to read the message and understand its meaning.

The spies use the only service that functions during the war period, the post. Each city has a postal agency where the letters are sent. The letters can be sent directly to their destination or to other postal agencies, until the letter arrives at the postal agency of the destination city, if possible.

The postal agency in city A can send a printed letter to the postal agency in city B if there is an agreement on sending letters, which determines the time, in hours, that a letter takes to reach city B from city A (and not necessarily the opposite). If there is no agreement between the agencies A and B, the agency A can try to send the letter to any agency so that the letter can reach its destination as early as possible

Some agencies are connected with electronic communication media, such as satellites and optical fibers. Before the war, these connections could reach all the agencies, making that a letter could be sent instantly. But during the period of hostilities every country starts to control electronic communication and an agency can only send a letter to another agency by electronic media (or instantly) if they are in the same country. Two agencies, A and B, are in the same country if a printed letter sent from any one of the agencies can be delivered to the other one.

The espionage service of your country has managed to obtain the content of all the agreements on sending messages existing in the world and desires to find out the minimum time to send a letter between different pairs of cities. Are you capable of helping them?

Input

The input contains several test cases. The first line of each test case contains two integer separated by a space, N (1 ≤ N ≤ 500) and E (0 ≤ EN2), indicating the numbers of cities (numbered from 1 to N) and of agreements on sending messages, respectively. Following them, then, E lines, each containing three integers separated by spaces, X, Y and H (1 ≤ X, YN, 1 ≤ H ≤ 1000), indicating that there exist an agreement to send a printed letter from city X to city Y, and that such a letter will be delivered in H hours.

After that, there will be a line with an integer K (0 ≤ K ≤ 100), the number of queries. Finally, there will be K lines, each representing a query and containing two integers separated by a space, O and D (1 ≤ O, DN). You must determine the minimum time to send a letter from city O to city D.

The end of the input is indicated by N = 0.

Output

For each test case your program should produce K lines of output. The I-th line should contain an integer M, the minimum time, in hours, to send a letter in the I-th query. If there aren’t communication media between the cities of the query, you should print “Nao e possivel entregar a carta” (“It’s impossible to deliver the letter”).

Print a blank line after each test case.

Sample Input

4 5
1 2 5
2 1 10
3 4 8
4 3 7
2 3 6
5
1 2
1 3
1 4
4 3
4 1
3 3
1 2 10
2 3 1
3 2 1
3
1 3
3 1
3 2
0 0

Sample Output

0
6
6
0
Nao e possivel entregar a carta
10
Nao e possivel entregar a carta
0

有人是这样描述的:  有向图的顶点集的一个子集,如果
该子集中的任何两个定点在原图中是互相可达的,则这
个顶点子集就是原图的一个强连通分量.

强连通分量的求法严蔚敏的数据结构书上有简单的介绍
那个算法被称作Kosaraju算法,分别对原图和逆图进行
一次DFS,先对逆图,记录下各个顶点退出DFS的时间,再
对原图,按从最晚退出DFS的定点开始,每一棵DFS树就是
一个强连通分量.求强连通分量的算法还有Gabow算法,
据说只要一次DFS即可,没找到资料.
强连通分量的一个重要应用场合就是对原图进行收缩.
每个强连通分量收缩成一个点,这样就会得到DAG图,
有了DAG图就可以进行拓补排序等操作从而解决很多
实际问题.

 

/*
强连通分量(Kosaraju)+缩点构图 + dijkstra
Waring:  flody超时

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Kosaraju算法:
1)首先对图G进行一次dfs,并记录下回溯的顺序。
2)把图G的所有边反向,得到图G’,并沿回溯顺序的倒序
(即时间戳从大到小)再进行一次dfs,所得的深度优先树即为强连通分量的划分。
*/

//5082521 Oak_Wesley 3114 Accepted 3516K 313MS C++ 3564B 2009-05-02 10:50:59 
#include <iostream>
#include 
<vector>
using namespace std;

const int N = 502;
const int MAX = 999999999;

vector
<int> xx[N];
vector
<int> yy[N];
bool Visited[N];
int graph[N][N];//原图
int new_graph[N][N];//求强连通分量,缩点后的图
int post[N], UFSet[N];
int dist[N];
int n, e;
int cnt;

void dfs1(int y)
{

    Visited[y] 
= true;
    
    
for(int i = 0;i < yy[y].size(); i++)
        
if(!Visited[yy[y][i]])
            dfs1(yy[y][i]);
            
    post[cnt
++= y;
}


void dfs2(int x)
{

    Visited[x] 
= true;
    UFSet[x] 
= cnt;

    
for(int i = 0; i < xx[x].size(); i++)
        
if(!Visited[xx[x][i]])
            dfs2(xx[x][i]);
}


void solve_connect()
{
    
int i, j;
    cnt 
= 0;
    
for(i = 1; i <= n; i++)
        
if(!Visited[i])
            dfs1(i);

    
for(i = 1; i <= n; i++)
        Visited[i] 
= false;
    cnt 
= 1;

    
for(i = n - 1; i >= 0; i--)
        
if(!Visited[post[i]])
        
{
            dfs2(post[i]);
            cnt
++;
        }

    cnt
--;
    
/*for(i = 1; i <= n; i++)
        cout<<UFSet[i]<<" ";
*/


    
for(i = 1; i <= cnt; i++)
        
for(j = 1; j <= cnt; j++)
            new_graph[i][j] 
= MAX;
    
for(i = 1; i <= n;i++)
    
{//构建求连通分量后的新图p
        for(j = 0; j < xx[i].size(); j++)
            
if(UFSet[i] != UFSet[xx[i][j]])
            
{//存在于二个连通分量中
                if(graph[i][xx[i][j]] != MAX)
                
{//可通
                    if(new_graph[UFSet[i]][UFSet[xx[i][j]]] == MAX ||
                        new_graph[UFSet[i]][UFSet[xx[i][j]]] 
> graph[i][xx[i][j]])
                        new_graph[UFSet[i]][UFSet[xx[i][j]]] 
= graph[i][xx[i][j]];
                }

            }

    }

}


/*
void flody()
{
    int i, j, k;
    for(k = 1; k <= cnt; k++)
        for(i = 1; i <= cnt; i++)
            for(j = 1; j <= cnt; j++)
                if(new_graph[i][k] + new_graph[k][j] < new_graph[i][j])
                    new_graph[i][j] = new_graph[i][k] + new_graph[k][j];

}
*/


void dijkstra(int x,int y)
{
    
int i,j,k,minv;

    
for(i=1;i <= cnt;i++)
    
{
        new_graph[i][i]
=0;             
        dist[i]
=new_graph[x][i];
        Visited[i] 
= false;             
     }

    Visited[x] 
= true;

    
for(i=1;i <= cnt;i++)
    
{
        minv
=MAX;
        j
=-1;
        
for(k=1;k <= cnt;k++)
        
{
            
if(!Visited[k]&&dist[k] < minv)
            
{
               j
=k;
               minv
=dist[k];                   
               }
             
            }

        
if(j==-1)break;       
        Visited[j] 
= true;
        
for(k=1;k <= cnt; k++)
        
{
            
if(!Visited[k]&&dist[j]+new_graph[j][k] < dist[k])
            
{
               dist[k]
=dist[j]+new_graph[j][k];                               
            }
                       
        }

    }
         
    
if(dist[y] != MAX)
        printf(
"%d\n",dist[y]);
    
else 
        printf(
"Nao e possivel entregar a carta\n");    
}


int main()
{
    
int i, j, k;
    
int x, y, h;
    
while(scanf("%d%d"&n, &e)!= EOF && n)
    
{
        
for(i = 1; i <= n; i++)
        
{
            
for(j = 1; j <= n; j++)
            
{//init
                graph[i][j] = MAX;    
            }

            Visited[i] 
= false;
            xx[i].clear();
            yy[i].clear();
        }


        
for(i = 0; i < e; i++)
        
{//input , create a graph
            scanf("%d%d%d"&x, &y, &h);
            xx[x].push_back(y);
            yy[y].push_back(x);
            graph[x][y] 
= h;
        }

        solve_connect();
        
//flody();
        scanf("%d"&k);

        
while(k--)
        
{
            scanf(
"%d%d"&i, &j);
            
if(UFSet[i] == UFSet[j])
                printf(
"0\n");
            
/*else
            {flody
                if(new_graph[UFSet[i]][UFSet[j]] == MAX)
                    printf("Nao e possivel entregar a carta\n");
                else
                    printf("%d\n", new_graph[UFSet[i]][UFSet[j]]);
            }
*/

            
else 
                dijkstra(UFSet[i], UFSet[j]);
        }

        putchar(
'\n');
    }

    
return 0;
}

posted on 2009-05-02 11:06  Xredman  阅读(331)  评论(0编辑  收藏  举报

导航