답안 #801944

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
801944 2023-08-02T08:34:03 Z vjudge1 Railway Trip (JOI17_railway_trip) C++17
0 / 100
2000 ms 15540 KB
#include<bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 1e5 + 10;
const int INF = 1e9 + 10;

vector<int> g[N];
int n, k, q;
int H[N];

vector<int> dist(N);
vector<int> pr(N);
void bfs(vector<int> st) {
    dist.assign(n + 1, INF);
    pr.assign(n + 1, -1);
    queue<int> q;
    vector<bool> vis(n + 1, false);
    int inx = 0;
    for(int c : st) {
        dist[c] = 0;
        vis[c] = 1;
        pr[c] = inx++;
        q.push(c);
    } 
    while(!q.empty()) {
        int s = q.front();
        q.pop();
        for(int to : g[s]) {
            if(vis[to]) continue;
            pr[to] = pr[s];
            dist[to] = dist[s] + 1;
            vis[to] = 1;
            q.push(to); 
        }
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin >> n >> k >> q;
    for(int i = 1; i <= n; i++) 
        cin >> H[i];
    vector<int> st;
    for(int i = 1; i <= n; i++) {
        while(!st.empty() && H[st.back()] < H[i]) {
            g[i].push_back(st.back());
            st.pop_back();
        }
        if(!st.empty()) 
            g[i].push_back(st.back());
        st.push_back(i);
    }
    st.clear();
    for(int i = n; i >= 1; i--) {
        while(!st.empty() && H[st.back()] < H[i]) {
            g[i].push_back(st.back());
            st.pop_back();
        }
        if(!st.empty()) 
            g[i].push_back(st.back());
        st.push_back(i);
    }
    st.clear();
    if(q <= 50) {
        while(q--) {
            int u, v;
            cin >> u >> v;
            bfs({u});
            cout << dist[v] - 1 << '\n';
        }
        return 0;
    }
    vector<int> t[k + 1];
    for(int i = 1; i <= n; i++) 
        t[H[i]].push_back(i);
    vector<int> res(q, INF);
    vector<pair<pair<int, int>, int>> qr;
    for(int i = 0; i < q; i++) {
        int u, v;
        cin >> u >> v;
        qr.push_back({{u, v}, i});
    }
    for(int i = k; i >= 1; i--) {
        bfs(t[i]);
        for(auto c : qr) {
            int u = c.first.first, v = c.first.second, ix = c.second;
            res[ix] = min(res[ix], dist[u] + dist[v] + abs(pr[u] - pr[v]));
        }
    }
    for(int i = 0; i < q; i++) 
        cout << res[i] - 1 << '\n';
}
# 결과 실행 시간 메모리 Grader output
1 Incorrect 2 ms 3472 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Incorrect 3 ms 3484 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Incorrect 92 ms 12232 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Execution timed out 2077 ms 15540 KB Time limit exceeded
2 Halted 0 ms 0 KB -