先強連通縮點處理處DAG圖,然後再DAG圖上求兩點間最短路就行了。。。用floyd算法會逾時。。
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 505
#define maxm 250005
#define eps 1e-10
#define mod 1000000009
#define INF 99999999
#define lowbit(x) (x&(-x))
//#define lson o<<1, L, mid
//#define rson o<<1 | 1, mid+1, R
typedef long long LL;
//typedef int LL;
using namespace std;
int H[maxn], NEXT[maxm], V[maxm], W[maxm];
int h[maxn], next[maxm], v[maxm], w[maxm];
int dfn[maxn], dis[maxn], low[maxn];
int ins[maxn], id[maxn], done[maxn];
int n, m, scc_cnt, top;
stack<int> s;
struct node
{
int x, d;
bool operator < (const node &a) const {
return a.d<d;
}
}temp, now;
priority_queue<node> q;
void init(void)
{
top = scc_cnt = 0;
memset(h, -1, sizeof h);
memset(H, -1, sizeof H);
memset(ins, 0, sizeof ins);
memset(dfn, 0, sizeof dfn);
}
void read(void)
{
int a, b, c, cnt = 0;
while(m--) {
scanf("%d%d%d", &a, &b, &c);
NEXT[cnt] = H[a], H[a] = cnt, V[cnt] = b, W[cnt] = c, cnt++;
}
}
void tarjan(int u)
{
dfn[u] = low[u] = ++top;
s.push(u), ins[u] = 1;
for(int e = H[u]; ~e; e = NEXT[e])
if(!dfn[V[e]]) {
tarjan(V[e]);
low[u] = min(low[u], low[V[e]]);
}
else if(ins[V[e]]) low[u] = min(low[u], dfn[V[e]]);
if(dfn[u] == low[u]) {
int tmp = s.top(); s.pop(), ins[tmp] = 0;
++scc_cnt;
while(tmp != u) {
id[tmp] = scc_cnt;
tmp = s.top();
s.pop();
ins[tmp] = 0;
}
id[tmp] = scc_cnt;
}
}
void narrow(void)
{
int cnt = 0;
for(int i = 1; i <= n; i++)
for(int e = H[i]; ~e; e = NEXT[e])
next[cnt] = h[id[i]], h[id[i]] = cnt, v[cnt] = id[V[e]], w[cnt] = W[e], cnt++;
}
void dijstra(int s)
{
for(int i = 0; i <= scc_cnt; i++) dis[i] = INF;
memset(done, 0, sizeof done);
dis[s] = 0, now.x = s, now.d = 0;
q.push(now);
while(!q.empty()) {
now = q.top();
q.pop();
if(done[now.x]) continue;
done[now.x] = 1;
for(int e = h[now.x]; ~e; e = next[e])
if(v[e] != now.x)
if(dis[v[e]] > dis[now.x] + w[e]) {
dis[v[e]] = dis[now.x] + w[e];
temp.x = v[e];
temp.d = dis[v[e]];
q.push(temp);
}
}
}
void work(void)
{
int a, b, i;
for(i = 1; i <= n; i++)
if(!dfn[i]) tarjan(i);
narrow();
scanf("%d", &m);
while(m--) {
scanf("%d%d", &a, &b);
a = id[a], b = id[b];
if(a == b) {
printf("0\n");
continue;
}
dijstra(a);
if(dis[b] != INF) printf("%d\n", dis[b]);
else printf("Nao e possivel entregar a carta\n");
}
printf("\n");
}
int main(void)
{
while(scanf("%d%d", &n, &m)&&n!=0) {
init();
read();
work();
}
return 0;
}