Submission #805286

#TimeUsernameProblemLanguageResultExecution timeMemory
805286thimote75Railway Trip (JOI17_railway_trip)C++14
20 / 100
2063 ms3276 KiB

#include <bits/stdc++.h>

using namespace std;

using idata = vector<int>;


template <typename A, typename B>
string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
string to_string(string s) { return s; }
template <typename T> string to_string(T v) {
	bool first = true;
	string res = "[";
	for (const auto &x : v) {
		if (!first)
			res += ", ";
		first = false;
		res += to_string(x);
	}
	res += "]";
	return res;
}

void dbg_out() { cout << endl; }
template <typename Head, typename... Tail> void dbg_out(Head H, Tail... T) {
	cout << ' ' << to_string(H);
	dbg_out(T...);
}

#ifdef DEBUG
#define dbg(...) cout << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif

struct Container {
    map<int, int> m;

    void insert(int height, int pos) {
        auto it = m.upper_bound(height);
        while (it != m.begin()) {
            it --;

            int h = (*it).first;
            m.erase(h);
            
            it = m.upper_bound(height);
        }

        m.insert({ height, pos });
    }

    int query (int height) {
        auto it = m.lower_bound(height);
        if (it == m.end()) return -1;

        return (*it).second;
    }
};

idata heights;

idata  left_road;
idata right_road;

int N, K, Q;

idata bfs (int start) {
    queue<int> q; 
    idata answer(N, 1e9);
    answer[start] = 0;
    q.push(start);

    while (q.size() != 0) {
        int curr = q.front(); q.pop();

        for (int next : { left_road[curr], right_road[curr] }) {
            if (next == -1) continue ;

            if (answer[next] != 1e9) continue ;
            q.push(next);
            answer[next] = answer[curr] + 1;
        }
    }

    return answer;
}

int main () {
    cin >> N >> K >> Q;

    heights.resize(N);
    for (int i = 0; i < N; i ++) cin >> heights[i];

    left_road.resize(N, -1);
    Container cnt;
    for (int i = 0; i < N; i ++) {
        left_road[i] = cnt.query(heights[i]);
        cnt.insert(heights[i], i);
    }

    cnt.m.clear();
    right_road.resize(N, -1);
    for (int i = N - 1; i >= 0; i --) {
        right_road[i] = cnt.query(heights[i]);
        cnt.insert(heights[i], i);
    }

    for (int q = 0; q < Q; q ++) {
        int a, b;
        cin >> a >> b;
        a --; b --;

        idata tA = bfs(a);
        idata tB = bfs(b);
        int res = 1e9;
        for (int i = 0; i < N; i ++)
            res = min(res, tA[i] + tB[i] - 1);
        
        cout << res << "\n";
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...