大佬帮忙给瞅瞅,90分,竟然没卡过去!
查看原帖
大佬帮忙给瞅瞅,90分,竟然没卡过去!
675208
coder2009楼主2024/7/11 21:33

90分,竟然没卡过去了,到底错在哪里呢?

#include <bits/stdc++.h>

using namespace std;
const int INF = 1e9;
const int maxn = 2e5 + 5;
struct edge {
    int to, next, w;
} g[1000005];
int head[maxn], cnt[maxn], n, m, k, t, a = 0, dist[maxn];
bool vis[maxn];
struct node {
    int idx, w;
};

bool operator< (const node& x, const node& y) {
    return x.w > y.w;
}

bool spfa(int s) {
    dist[s] = 0;
    vis[s] = true;
    priority_queue<node> q;
    q.push({s, 0});
    while (!q.empty()) {
        auto u = q.top();
        q.pop();
        if (++cnt[u.idx] >= n) {
            return false;
        }
        vis[u.idx] = false;
        for (int i = head[u.idx]; i; i = g[i].next) {
            auto v = g[i];
            if (dist[v.to] > dist[u.idx] + v.w) {
                dist[v.to] = dist[u.idx] + v.w;
                if (!vis[v.to]) {
                    vis[v.to] = true;
                    q.push({v.to, dist[v.to]});
                }
            }
        }
    }
    return true;
}

void add(int u, int v, int w) {
    g[++a].to = v;
    g[a].w = w;
    g[a].next = head[u];
    head[u] = a;
}

void best_coder() {
    cin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int u, v;
        cin >> u >> v;
        add(u - 1, v, 1);
        add(v, u - 1, -1);
    }
    for (int i = 1; i <= n; ++i) {
        add(i, i - 1, 0);
        add(i - 1, i, 1);
        dist[i] = INF;
    }
    if (!spfa(0)) {
        cout << -1;
        return;
    }
    cout << dist[n];
}


void happy_coder() {

}

int main() {
    // 提升cin、cout效率
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    // 小码匠
    best_coder();

    // 最优解
    // happy_coder();

    return 0;
}
2024/7/11 21:33
加载中...