HDU 1548 A strange lift SPFA

/*
 * 可以將由當前點能一步到達的點連上一條邊,然後跑最短路模板就行了。
 */
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e2 + 10;
const int MAXM = 4e2 + 10;
const int INF = 0x3f3f3f3f;

struct E{
    int to, w, nxt;
}edge[MAXM];
int tot;
int head[MAXN];
queue<int> q;
int dis[MAXN];
bool inq[MAXN];
int inqcnt[MAXN];
int n, s, e;

inline void clear(){
    tot = 0;
    memset(head, -1, sizeof head);
    while(!q.empty()) q.pop();
    memset(dis, INF, sizeof dis);
    dis[s] = 0;
    memset(inq, false, sizeof inq);
    memset(inqcnt, 0, sizeof inqcnt);
}

inline void addedge(int u, int v, int w){
    edge[tot].to = v;
    edge[tot].w = w;
    edge[tot].nxt = head[u];
    head[u] = tot++;
}

inline bool SPFA(){
    q.push(s);
    inq[s] = true;
    ++inqcnt[s];
    while(!q.empty()){
        int id = q.front();
        q.pop();
        inq[id] = false;
        for(int i = head[id]; ~i; i = edge[i].nxt){
            int to = edge[i].to;
            int w = edge[i].w;
            if(dis[id] + w < dis[to]){
                dis[to] = dis[id] + w;
                if(!inq[to]){
                    q.push(to);
                    inq[to] = true;
                    ++inqcnt[to];
                    if(inqcnt[to] > n) return false;
                }
            }
        }
    }
    return true;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    //cout << setiosflags(ios::fixed) << setprecision(1); //保留小數點後1位
    //cout << setprecision(1); //保留1位有效數字
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);

    while(cin >> n){
        if(n == 0) break;
        cin >> s >> e;
        clear();
        for(int i = 1, x; i <= n; ++i){
            cin >> x;
            if(i - x >= 1 && i - x <= n) addedge(i, i - x, 1);
            if(i + x >= 1 && i + x <= n) addedge(i, i + x, 1);
        }
        bool ok = SPFA();
        if(!ok) continue;
        if(dis[e] == INF) cout << -1 << endl;
        else cout << dis[e] << endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章