题意:给定一个n节点m条边的无向图,定义c为每对顶点的最短路之和,要求删掉一条边重新求一个c值c',求出c'最大值.
思路:如果用floyd算法计算c,每尝试删除一条边都要重新计算一次,时间复杂度为O(n*n*n*m),很难承受。如果用n次Dijkstra计算单源最短路,时间复杂度味O(n*m*m*logn)。虽然看上去比之前的好,但由于佛洛依德算法的常数很小,实际运行时间差不多。这时候,可以考虑最短路树。因为在源点确定的情况下,只要最短路树不被破坏,起点到所有点的距离都不会发生改变。也就是说,只有删除最短路树上的n-1条边,最短路树才需要重新计算。这样,对于每个源点,最多只需求n次最短路而不是m次,时间复杂度降为O(n*n*m*logn),可以承受。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#define eps 1e-6
#define LL long long
using namespace std;
const int maxn = 155 + 5;
const int INF = 1000000000;
int n, m, L;
//Dijkstra
struct Edge {
int from, to, dist;
Edge(int u = 0, int v = 0, int d = 0) : from(u), to(v), dist(d) {
}
};
struct HeapNode { ///用到的优先队列的结点
int d, u;
bool operator < (const HeapNode& rhs) const {
return d > rhs.d;
}
};
struct Dijkstra {
int n, m; //点数和边数
vector<Edge> edges; //边列表
vector<int> G[maxn]; //每个节点出发的边编号
bool done[maxn]; //是否已经永久编号
int d[maxn]; //s到各个点的距离
int p[maxn]; //最短路中的上一条边
int del;
void init(int n) {
this->n = n;
for(int i = 0; i < n; i++) G[i].clear();
edges.clear();
del = -1;
}
void AddEdge(int from, int to, int dist) { //如果是无向图需要调用两次
edges.push_back(Edge(from, to, dist));
m = edges.size();
G[from].push_back(m-1);
}
LL dijkstra(int s) { //求s到所有点的距离
priority_queue<HeapNode> Q;
for(int i = 0; i < n; i++) d[i] = INF;
d[s] = 0;
memset(done, 0, sizeof(done));
memset(p, -1, sizeof(p));
Q.push((HeapNode){0, s});
while(!Q.empty()) {
HeapNode x = Q.top(); Q.pop();
int u = x.u;
if(done[u]) continue;
done[u] = true;
for(int i = 0; i < G[u].size(); i++) if(G[u][i]!=del && G[u][i]!=(del^1)){
Edge& e = edges[G[u][i]];
if(d[e.to] > d[u] + e.dist) {
d[e.to] = d[u] + e.dist;
p[e.to] = G[u][i];
Q.push((HeapNode){d[e.to], e.to});
}
}
}
LL ans = 0;
for(int u = 0; u < n; u++) if(u != s) {
if(d[u] == INF) ans += L;
else ans += d[u];
}
return ans;
}
} solver;
LL ans[2055]; int parent[maxn];
void init() {
solver.init(n);
memset(ans, 0, sizeof(ans));
int u, v, d;
for(int i = m-1; i >= 0; i--) {
scanf("%d%d%d", &u, &v, &d);
u--; v--;
solver.AddEdge(u, v, d);
solver.AddEdge(v, u, d);
}
}
void solve() {
LL preans = 0;
for(int s = 0; s < n; s++) {
int len = solver.dijkstra(s);
for(int i = 0; i < n; i++) parent[i] = solver.p[i];
preans += len;
for(int i = 0; i < 2*m; i++) ans[i] += len;
for(int son = 0; son < n; son++) if(son != s){
if(parent[son] == -1) continue;
solver.del = parent[son];
ans[parent[son]] = ans[parent[son]^1] = ans[parent[son]] + solver.dijkstra(s) - len;
}
solver.del = -1;
}
LL del_ans = 0;
for(int i = 0; i < 2*m; i++) del_ans = max(del_ans, ans[i]);
cout << preans << " " << del_ans << endl;
//for(int i = 0; i < 2*m; i++) cout << ans[i] << endl;
}
int main() {
//freopen("input.txt", "r", stdin);
while(scanf("%d%d%d", &n, &m, &L) == 3) {
init();
solve();
}
return 0;
}