POJ 3114 countries in War strong connectivity Tarjan contraction point after running shortest path SPFA

Source: Internet
Author: User
Tags in degrees printf
Countries in War
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2359 Accepted: 736

Description

In the year 2050, after different attempts of the UN-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 ESP Ionage services, so, all of the world have at least one spy's each country. These spies need to communicate and other spies, informers as well as their headquarters during their actions. Unluckily there doesn ' t exist a secure a-to-a spy to communicate during the war period, therefore the messages is Alwa Ys sent in code so, only the addressee are 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 is sent. The letters can 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 are an agreement on Sendin G letters, which determines the time, in hours, which a letter takes to reach city B from City a (and not necessarily the O Pposite). 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 L Etter can reach its destination as early as possible

Some agencies is 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 a agency can only send A letter to another agency by electronic media (or instantly) if they is in the same country. Agencies, A and B, is in the same country if A printed letter sent from any one of the agencies can is delivered to T He and other one.

The espionage service of your country have 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. Is you capable of helping them?

Input

The

The input contains several test cases. The first line of all test case contains, separated by a space, n  (1≤ n ≤500) and e   (0≤ E ≤ N2), indicating the numbers of cities (numbered from 1 to n) and of agreements on Sendi ng messages, respectively. Following them, Then, e lines, each containing three integers separated by spaces, x, y and& nbsp h  (1≤ x, y ≤ n, 1≤ h ≤1000), indicating, there exist an agreement to send a prin Ted Letter from City x to City y, and that such a letter would be delivered in h hours.

After that, there'll is a line with an integer K (0≤k≤100), the number of queries.  Finally, there would be the K lines, each representing a query and containing the integers separated by a space, O and D (1≤o, D≤n). 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 the 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 Ten
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
nao e possivel entregar a carta
0



The title says that there are N cities in wartime, and some cities can pass information one way. If, 22 of a few cities can pass information to each other, it means that they are a country.

The e-input indicates which pairs of cities can be connected, x->y time-consuming H.

The transmission of information between a country can be done instantaneously.    So this is a forward-and-loop graph. By Tarjan the point of indentation.  Go after the ring. Find the shortest distance between each country, that is, each strong connected component. Then run a change SPFA, you can draw two points of the shortest transmission time.

If unable to transmit to output Nao e possivel entregar a carta;

#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; #include <vector> #include <queue> #define INF 1000000000 int min (int a,int b) {return a>b?b:a;} int max (  int A,int b) {return a<b?b:a;} #define N//n is the maximum number of points #define M 250000//m for maximum edge int N, m;//n M for points and number of edges struct  
    edge{int from, to, NEX, Len;  
Whether the bool sign;//is a bridge}edge[m<<1];  
int head[n], edgenum;  
    void Add (int u, int v, int len) {//edge start and End Edge E={u, V, Head[u], Len, false};  
    Edge[edgenum] = E;  
Head[u] = edgenum++; } int dfn[n], low[n], Stack[n], top, time; Low[u] is the point set {U-point and subtree in the root of the U-point} (all reverse arcs) can point to (the nearest ancestor of the Root v) dfn[v] value (i.e. V-point timestamp) int taj;//Connected Branch label, starting from 1 int belong[n];//belong[i] represents I point  
Belonging to the connected branch bool Instack[n]; Vector<int> Bcc[n];    
    Marking starting from 1 void Tarjan (int u, int fa) {Dfn[u] = Low[u] = + + time;    
    Stack[top + +] = u;   
    Instack[u] = 1;    
  for (int i = head[u]; ~i; i = Edge[i].nex) {      int v = edge[i].to;    
            if (dfn[v] = =-1) {Tarjan (V, u);  
            Low[u] = min (Low[u], low[v]); if (Dfn[u] < Low[v]) {edge[i].sign = 1;//is Cut Bridge}} El        
		Se if (instack[v]) {Low[u] = min (Low[u], dfn[v]);  
        }} if (low[u] = = Dfn[u]) {int now; 
		Taj + +;  
        Bcc[taj].clear ();    
            do{now = stack[--top];   
            Instack[now] = 0;  
            Belong [Now] = Taj;  
        Bcc[taj].push_back (now);  
    }while (now! = u);  
    }} void Tarjan_init (int all) {memset (DFN,-1, sizeof (DFN));  
    memset (instack, 0, sizeof (instack));  
    top = time = Taj = 0; for (int i=1;i<=all;i++) if (dfn[i]==-1) Tarjan (i, I);  
Note the start point label ...  
} vector<int>g[n];   int du[n];  
    In degrees void Suodian () {memset (Du, 0, sizeof (DU)); for (int i = 1; I <= Taj; i++) g[i].clear ();  
        for (int i = 0; i < Edgenum; i++) {int u = belong[edge[i].from], v = belong[edge[i].to];  
		if (u!=v) {g[u].push_back (v), du[v]++;
}}}//Shortest way int mp[600][600],dist[600];//for each point u in the original, it belongs to a new point in the new diagram Belong[u];


BOOL visit[600]; void SPFA (int sta)//SPFA algorithm//The same point is enqueued greater than or equal to the number of points.
is to have a negative ring, write their own.
    {int I, now;
    Memset (visit, false, sizeof (visit));
    for (i = 1; I <= Taj; i++) dist[i] = inf;
    Dist[sta] = 0;
    Queue<int> Q;
    Q.push (STA);
    Visit[sta] = true; while (!
        Q.empty ()) {now = Q.front ();
        Q.pop ();
        Visit[now] = false; for (i = 1; I <= Taj; i++)//With now as the middle point.   Go through it again and see if there is a shorter way to I point.
        Vis for faster, do not repeat updates.
                {if (Dist[i] > Dist[now] + mp[now][i]) {dist[i] = Dist[now] + mp[now][i];
                    if (visit[i] = = 0) {Q.push (i);
                Visit[i] = true;
}
            }        }}} void Init () {memset (head,-1, sizeof (head)); edgenum=0;}
		int main () {while (scanf ("%d%d", &n,&m), n) {init ();
		int a,b,c;
				for (int i=1;i<=n;i++) {for (int j=1;j<=n;j++) {if (i==j) mp[i][j]=0;
			else Mp[i][j]=inf;
			}} for (int i=0;i<m;i++) {scanf ("%d%d%d", &a,&b,&c);
		Add (A,B,C);
		} tarjan_init (n);
		Suodian (); for (int i=0;i<m;i++) {if (Mp[belong[edge[i].from]][belong[edge[i].to]]>edge[i].len) Mp[belong[edge[i].from]
		][belong[edge[i].to]]=edge[i].len;
		} int q;
		scanf ("%d", &q);
			while (q--) {scanf ("%d%d", &a,&b);
			if (Belong[a]==belong[b]) printf ("0\n");
				else {SPFA (belong[a]);
				if (Dist[belong[b]]==inf) puts ("Nao e possivel Entregar a Carta");
			else printf ("%d\n", Dist[belong[b]]);
	}} puts ("");
} return 0;  }





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.