[hdu 5521 Meeting] 拆边 + Dijkstra
题目链接:[hdu 5521 Meeting] 拆点 + Dijkstra
题意描述:给定
N
个顶点,编号从
解题思路:这个题目还是具有一定的技巧性的。考虑这个最短路问题,可能关键的问题是如何存边。我这里用到了拆边的技巧。也就是,对于每个集合
Si
我新增一个顶点,集合中所有的顶点都连接到这个新增的顶点上,边长就是
ti2
,考虑到浮点误差,不妨先将边长扩大两倍。最后统计的时候再除2。
分别对顶点
1
和顶点
min{max{dij1.cost[u],dij2.cost[u]}}(1≤u≤N)
#include <bits/stdc++.h>
using namespace std;
#define FIN freopen("input.txt", "r", stdin)
typedef __int64 LL;
const int MAXN = 1e6 + 5;
const int MAXE = 1e6 + 5;
const LL INF = 0x3f3f3f3f3f3f3f3fLL;
int T, cas;
int N, M;
LL ans;
set<int> res;
set<int>::iterator iter;
struct Edge {
int v, next;
LL w;
Edge() {}
Edge(int v, LL w, int next) : v(v), w(w), next(next) {}
} edges[MAXE << 1];
int head[MAXN], ESZ;
LL dp[MAXN];
void init() {
ESZ = 0;
memset(head, -1, sizeof(head));
res.clear();
}
void add_edge(int u, int v, LL w) {
edges[ESZ] = Edge(v, w, head[u]);
head[u] = ESZ ++;
}
struct Dijkstra {
struct QNode {
int u;
LL cost;
QNode() {}
QNode(int u, LL cost) : u(u), cost(cost) {}
bool operator > (const QNode& e)const {
return cost > e.cost;
}
} cur;
bool used[MAXN];
LL cost[MAXN];
priority_queue<QNode, vector<QNode>, greater<QNode> > Q;
void init() {
memset(used, false, sizeof(used));
memset(cost, 0x3f, sizeof(cost));
}
void run(int src) {
int u, v;
LL w;
Q.push(QNode(src, cost[src] = 0));
while(!Q.empty()) {
cur = Q.top();
Q.pop();
u = cur.u;
if(used[u]) continue;
used[u] = true;
for(int i = head[u]; ~i; i = edges[i].next) {
v = edges[i].v, w = edges[i].w;
if(!used[v] && cost[v] > cost[u] + w) {
Q.push(QNode(v, cost[v] = cost[u] + w));
}
}
}
}
} dij1, dij2;
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
int n, u, v;
LL w;
cas = 0;
scanf("%d", &T);
while(T --) {
init();
scanf("%d %d", &N, &M);
u = N;
for(int i = 0; i < M; i++) {
scanf("%I64d %d", &w, &n);
u ++;
while(n --) {
scanf("%d", &v);
add_edge(u, v, w);
add_edge(v, u, w);
}
}
dij1.init();
dij1.run(1);
if(dij1.cost[N] == INF) {
printf("Case #%d: Evil John\n", ++cas);
continue;
}
for(u = 1; u <= N; u++) {
dp[u] = dij1.cost[u] >> 1;
}
dij2.init();
dij2.run(N);
for(u = 1; u <= N; u++) {
dp[u] = max(dp[u], dij2.cost[u] >> 1);
}
ans = INF;
for(u = 1; u <= N; u++) {
ans = min(ans, dp[u]);
}
printf("Case #%d: %I64d\n", ++cas, ans);
for(u = 1; u <= N; u++) {
if(ans != dp[u]) continue;
if(dp[u] == (dij1.cost[u] >> 1) || dp[u] == (dij2.cost[u] >> 1)) {
res.insert(u);
}
}
for(iter = res.begin(); iter != res.end(); iter++) {
if(iter != res.begin()) printf(" ");
printf("%d", *iter);
}
printf("\n");
}
return 0;
}