大意不再赘述。
思路:很简单、直接的一道题。首先通过强连通缩点,然后重建图,之后通过spfa找最小值。
重建图时:在一个国家之内的点,边权值为0,与其他的国家之间的边权值不变。
输出的时候有一个KD的BUG,害我找了N久。
#include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> #include <queue> using namespace std; const int MAXN = 510; const int MAXM = 510*510; const int INF = 0x3f3f3f3f; struct Edge { int v, w; int next; }edge[MAXM], edge2[MAXM]; int n, m; int cnt, cnt2; int scnt, top, tot; int first[MAXN], low[MAXN], dfn[MAXN], stack[MAXN], ins[MAXN]; int d[MAXN]; int first2[MAXN]; int belong[MAXM]; char str[51] = "Nao e possivel entregar a carta"; void init() { cnt = cnt2 = 0; scnt = top = tot = 0; memset(first, -1, sizeof(first)); memset(first2, -1, sizeof(first2)); memset(dfn, 0, sizeof(dfn)); memset(ins, 0, sizeof(ins)); } void read_graph(int u, int v, int w) { edge[cnt].v = v, edge[cnt].w = w; edge[cnt].next = first[u], first[u] = cnt++; } void read_graph2(int u, int v, int w) { edge2[cnt2].v = v, edge2[cnt2].w = w; edge2[cnt2].next = first2[u], first2[u] = cnt2++; } void dfs(int u) { int v; dfn[u] = low[u] = ++tot; stack[top++] = u; ins[u] = 1; for(int e = first[u]; e != -1; e = edge[e].next) { v = edge[e].v; if(!dfn[v]) { dfs(v); low[u] = min(low[u], low[v]); } else if(ins[v]) { low[u] = min(low[u], dfn[v]); } } if(dfn[u] == low[u]) { scnt++; do { v = stack[--top]; belong[v] = scnt; ins[v] = 0; }while(u != v); } } void Tarjan() { for(int v = 1; v <= n; v++) if(!dfn[v]) dfs(v); } void spfa(int src) { queue<int> q; bool inq[MAXN] = {0}; for(int i = 1; i <= n; i++) d[i] = (i == src) ? 0:INF; q.push(src); while(!q.empty()) { int x = q.front(); q.pop(); inq[x] = 0; for(int e = first2[x]; e != -1; e = edge2[e].next) { int v = edge2[e].v , w = edge2[e].w; if(d[v] > d[x] + w) { d[v] = d[x] + w; if(!inq[v]) { inq[v] = 1; q.push(v); } } } } } int read_case() { init(); scanf("%d", &n); if(!n) return 0; scanf("%d", &m); while(m--) { int u, v, w; scanf("%d%d%d", &u, &v, &w); read_graph(u, v, w); } return 1; } void build() { Tarjan(); for(int u = 1; u <= n; u++) { for(int e = first[u]; e != -1; e = edge[e].next) { int v = edge[e].v, w = edge[e].w; if(belong[u] != belong[v]) { read_graph2(u, v, w); } else read_graph2(u, v, 0); } } } void solve() { int q; build(); scanf("%d", &q); while(q--) { int s, e; scanf("%d%d", &s, &e); spfa(s); //printf(d[e] != INF? "%d\n":"%s\n", d[e], str); KD的BUG,这样输出的永远是错误答案,害我找了N久。 if(d[e] != INF) printf("%d\n", d[e]); else printf("%s\n", str); } printf("\n"); } int main() { while(read_case()) { solve(); } return 0; }