题意
给出一个坐标图,图上两点以及两点的距离,求一个距离最短的环的路程。
思路
枚举任意一条边,然后以其中一点为起点跑迪杰斯特拉。
学习一下边枚举方法,以及迪杰斯特拉堆优化的写法。
坐标需要用map hash成一个数。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 8400, inf = 0x3f3f3f3f;
typedef pair<int, int> Pair;
int n, cnt, tot;
map<Pair, int> mp;
int head[maxn];
struct heapnode {
int u, cost;
heapnode(int u, int cost) : u(u), cost(cost) {}
bool operator < (const heapnode& rhs) const {
return cost > rhs.cost;
}
};
struct EE {
int u, v, cost;
} ee[maxn];
struct E {
int to, cost, nxt;
} e[maxn];
void init() {
mp.clear();
memset(head, -1, sizeof(head));
tot = 0;
cnt = 0;
}
int d[maxn], vis[maxn];
int solve(int x) {
int from = ee[x].u, to = ee[x].v;
for(int i = 1; i <= tot; i++) {
d[i] = inf, vis[i] = 0;
}
d[from] = 0;
priority_queue<heapnode> pq;
pq.push(heapnode(from, 0));
while(!pq.empty()) {
heapnode tmp = pq.top(); pq.pop();
int u = tmp.u;
if(u == to) return d[u];
if(vis[u]) continue;
vis[u] = 1;
for(int i = head[u]; i != -1; i = e[i].nxt) {
int v = e[i].to;
int c = e[i].cost;
if(v == to && u == from) continue;
if( d[v] > d[u] + c) {
d[v] = d[u] + c;
pq.push(heapnode(v, d[v]));
}
}
}
return -1;
}
void addEdge(int from, int to, int cost) {
e[cnt].to = to;
e[cnt].cost = cost;
e[cnt].nxt = head[from];
head[from] = cnt++;
}
int main() {
//ios::sync_with_stdio(false);
//freopen("i.txt", "r", stdin);
int x,y,xx,yy;
int T; cin >> T;
int cas = 0;
while(T--) {
init();
scanf("%d", &n);
//cout << n << "--------------------------" << endl;
for(int i = 0; i < n; i++) {
cin >> x >> y >> xx >> yy >> ee[i].cost;
Pair p1(x,y);
Pair p2(xx,yy);
if(!mp.count(p1)) {
mp[p1]=(++tot);
}
if (!mp.count(p2)) {
mp[p2] = (++tot);
}
ee[i].u = mp[p1];
ee[i].v = mp[p2];
addEdge(ee[i].u, ee[i].v, ee[i].cost);
addEdge(ee[i].v, ee[i].u, ee[i].cost);
}
// cout << "tot" << tot << endl;
int ans = inf;
for(int i = 0; i < n; i++) {
int res = solve(i);
//cout << "=============== " << endl;
if(res != -1) {
//cout << "213123" << endl;
ans = min(ans, res + ee[i].cost);
}
}
if(ans == inf) {
ans = 0;
}
printf("Case #%d: %d\n", ++cas, ans);
}
return 0;
}
/*
2
5
0 0 0 1 2
0 0 1 0 2
0 1 1 1 2
1 0 1 1 2
1 0 0 1 5
9
1 1 3 1 1
1 1 1 3 2
3 1 3 3 2
1 3 3 3 1
1 1 2 2 2
2 2 3 3 3
3 1 2 2 1
2 2 1 3 2
4 1 5 1 4
*/