UVA 10801 - Lift Hopping (Dijkstra算法/最短路)

比较简单的最短路问题,唯一的不同是更换电梯的时候需要多加60s等待时间,而且第一次上电梯不需要等待60s 。注意到这些细节之后在结构体中多保存一个电梯的id,这样在松弛操作的时候分情况讨论一下就行了 。

细节参见代码:

#include<bits/stdc++.h>
using namespace std;
const double INF = 1000000000;
const int maxn = 505;
int n,k,done[maxn],kase = 0,cur,t[maxn],a[maxn];
int d[maxn];
char s[maxn];
struct Node {
    int from,to,d,id;
    Node(int from=0,int to=0,int d=0,int id=0):from(from),to(to),d(d),id(id) {}
}e[maxn*maxn] ;
vector<int> g[maxn];
struct heapNode{
    int d,u,id;
    bool operator < (const heapNode& rhs) const {
        return d > rhs.d;
    }
};
int dijkstra(int s) {
    priority_queue<heapNode> q;
    for(int i=0;i<100;i++) d[i] = INF , done[i] = 0;
    d[s] = 0;
    q.push((heapNode){0,s,-1});
    while(!q.empty()) {
        heapNode x = q.top(); q.pop();
        int u = x.u;
        if(u == k) return d[u];
        if(done[u]) continue;
        done[u] = true;
        for(int i=0;i<g[u].size();i++) {
            Node& ed = e[g[u][i]];
            if(ed.id != x.id && x.id != -1) 
                if(d[ed.to] > d[u] + ed.d + 60) {
                    d[ed.to] = d[u] + ed.d + 60;
                    q.push((heapNode){d[ed.to],ed.to,ed.id});
                }
            else {
                if(d[ed.to] > d[u] + ed.d) {
                    d[ed.to] = d[u] + ed.d;
                    q.push((heapNode){d[ed.to],ed.to,ed.id});
                }
            }
        }
    }
    return -1;
}
int main() {
    while(~scanf("%d%d",&n,&k)) {
        for(int i=0;i<n;i++) scanf("%d",&t[i]) ;
        for(int i=0;i<100;i++) g[i].clear();
        cur = 0; char c = getchar();
        for(int i=0;i<n;i++) {
            gets(s);
            int len = strlen(s) , v = 0 , cnt = 0;
            for(int j=0;j<len;j++) {
                if(s[j] == ' ') { a[cnt++] = v; v= 0; }
                else v = v*10 + s[j]-'0';
                if(j == len-1) a[cnt++] = v;
            }
            for(int k=0;k<cnt;k++) //建图
                for(int j=0;j<cnt;j++) {
                    if(k == j) continue;
                    e[cur] = Node(a[k],a[j],abs(a[k]-a[j])*t[i],i);
                    g[a[k]].push_back(cur++);
                }
        }
        int ans = dijkstra(0);
        if(ans == -1) printf("IMPOSSIBLE\n");
        else printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(图论,最短路,dijkstra,uva,ACM-ICPC)