dijkstra求最小环,要先将坐标变为序号,然后删除每一条边,再求最短路,最后再与删除边的边权相加。
代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<queue>
#include<vector>
#include<stack>
//#define int long long
using namespace std;
typedef pair<int, int>PII;
const int inf = 1e9 + 7;
int cnt = 0;
struct edge {
int v, cost;
edge(int v1 = 0, int w = 0) { v = v1, cost = w; }
};
vector<edge>G[8003];
void addedge(int u, int v, int w) {
G[u].push_back(edge(v, w));
}
struct Edge {
int u, v, w;
Edge(int u1 = 0, int v1 = 0, int w1 = 0) { u = u1, v = v1, w = w1; }
}E[8003];
int vis[8003];
struct node {
int v, c;
node(int v1 = 0, int c1 = 0) { v = v1, c = c1; }
bool operator<(const node &a)const {
if (c == a.c)return v < a.v;
else
return c > a.c;
}
};
int ans = inf;
int dist[8003];
void dij(int st, int ed, int c) {
for (int i = 1; i <= cnt; i++)dist[i] = inf;
memset(vis, 0, sizeof(vis));
priority_queue<node>q;
while (!q.empty())q.pop();
dist[st] = 0;
q.push(node(st, 0));
while (!q.empty()) {
node next = q.top();
q.pop();
int u = next.v;
if (next.c + c > ans)break;
if (vis[u])continue;
vis[u] = 1;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].v;
int cost = G[u][i].cost;
if ((u == st && v == ed) || (u == ed && v == st))continue;
if (!vis[v] && dist[v] > dist[u] + cost) {
dist[v] = dist[u] + cost;
q.push(node(v, dist[v]));
}
}
}
}
void Init(int n) {
for (int i = 1; i <= n; i++)G[i].clear();
}
signed main()
{
int t;
scanf("%lld", &t);
int k = 1;
while (t--) {
cnt = 0;
map<PII, int>mp;
int m;
scanf("%lld", &m);
Init(m << 1);
int x1, y1, x2, y2, w;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &w);
if (!mp[PII(x1, y1)])mp[PII(x1, y1)] = ++cnt;
if (!mp[PII(x2, y2)])mp[PII(x2, y2)] = ++cnt;
int u = mp[PII(x1, y1)], v = mp[PII(x2, y2)];
addedge(u, v, w);
addedge(v, u, w);
E[i] = Edge(u, v, w);
}
ans = inf;
for (int i = 1; i <= m; i++) {
if (E[i].w > ans)continue;
dij(E[i].u, E[i].v, E[i].w);
ans = min(ans, E[i].w + dist[E[i].v]);
}
printf("Case #%d: %d\n", k++, ans == inf ? 0 : ans);
}
return 0;
}