# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
72713 | ikura355 | Railway Trip (JOI17_railway_trip) | C++14 | 4 ms | 560 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 5;
const int inf = 1e9;
int n,k,m;
int a[maxn];
int st[maxn], ft[maxn];
int dq[maxn];
int len1[maxn], len2[maxn];
vector<int> way[maxn];
queue<int> q;
void init() {
int sz = 0;
for(int x=1;x<=n;x++) {
int l = 1, r = sz, mid, pos = -1;
while(l<=r) {
mid = (l+r)/2;
if(a[x] <= a[dq[mid]]) {
pos = dq[mid];
l = mid+1;
}
else r = mid-1;
}
if(pos!=-1) {
way[x].push_back(pos);
// printf("%d - %d\n",x,pos);
}
dq[++sz] = x;
while(sz>=2 && a[dq[sz-1]] <= a[dq[sz]]) dq[sz-1] = dq[sz], sz--;
}
sz = 0;
for(int x=n;x>=1;x--) {
int l = 1, r = sz, mid, pos = -1;
while(l<=r) {
mid = (l+r)/2;
if(a[x] <= a[dq[mid]]) {
pos = dq[mid];
l = mid+1;
}
else r = mid-1;
}
if(pos!=-1) {
way[x].push_back(pos);
// printf("%d - %d\n",x,pos);
}
dq[++sz] = x;
while(sz>=2 && a[dq[sz-1]] <= a[dq[sz]]) dq[sz-1] = dq[sz], sz--;
}
}
int solve(int x, int y) {
for(int i=1;i<=n;i++) len1[i] = len2[i] = inf;
len1[x] = 0;
q.push(x);
while(!q.empty()) {
int u = q.front(); q.pop();
for(auto v : way[u]) {
if(len1[v] > len1[u] + 1) {
len1[v] = len1[u] + 1;
q.push(v);
}
}
}
len2[y] = 0;
q.push(y);
while(!q.empty()) {
int u = q.front(); q.pop();
for(auto v : way[u]) {
if(len2[v] > len2[u] + 1) {
len2[v] = len2[u] + 1;
q.push(v);
}
}
}
int ans = inf;
for(int i=1;i<=n;i++) {
ans = min(ans, len1[i] + len2[i] - 1);
}
return ans;
}
int main() {
scanf("%d%d%d",&n,&k,&m);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<=m;i++) scanf("%d%d",&st[i],&ft[i]);
init();
for(int i=1;i<=m;i++) printf("%d\n",solve(st[i],ft[i]));
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |