Input
第一行是一个正整数,表示测试数据的组数,
对于每组测试数据,
第一行是一个整数,分别表示连接京师路与木铎路,木铎路与金声路,金声路与新街口外大街的道路个数,
第二行包含个以空格分隔的整数,表示连接京师路与木铎路的各个小道的南北方向坐标(单位:m),
第三行包含个以空格分隔的整数,表示连接木铎路与金声路的各个小道的南北方向坐标(单位:m),
第四行包含个以空格分隔的整数,表示连接金声路与新街口外大街的各个小道的南北方向坐标(单位:m),
保证每行坐标按严格递增的顺序给出,并且坐标绝对值不超过。
Output
对于每组测试数据,输出一行,包含一个整数,表示答案(单位:s)。
Sample Input
1 3 3 2 -1 1 4 -3 2 4 -1 1
Sample Output
5
Source
Author
#include<algorithm> #include<iostream> #include<queue> #include<cstdio> #include<climits>using namespace std;const int N = 100000 + 5; using LL = long long; LL a[N], b[N], B[N], c[N], C[N]; int n, m, k;struct node{LL x, sum, s;node(LL x, LL sum, LL s){this -> x = x;this -> sum = sum;this -> s = s;}bool operator < (const node & m) const {return sum > m.sum;} };queue<node> Q;void DFS(){for(int i = 0; i < n; i++){Q.push((node){a[i], 1, 1});}while(!Q.empty()){node t = Q.front(); Q.pop();if(t.s == 1){LL *p = lower_bound(b, b + m, t.x);int tt = distance(b, p);if(tt < m - 1){LL y = b[tt+1];LL sum = t.sum + abs(t.x - y);if(sum < B[tt+1]){Q.push((node){y, sum + 1, 2});B[tt+1] = sum;}}if(tt != m){LL y = b[tt];LL sum = t.sum + abs(t.x - y);if(sum < B[tt]) {B[tt] = sum;Q.push((node){y, sum + 1, 2});}}if(tt != 0){LL y = b[tt-1];LL sum = t.sum + abs(t.x - y);if(sum < B[tt-1]) {B[tt-1] = sum;Q.push((node){y, sum + 1, 2});}}}if(t.s == 2){LL *p = lower_bound(c, c + k, t.x);int tt = distance(c, p);if(tt < k-1){LL y = c[tt + 1];LL sum = t.sum + abs(t.x - y);if(sum < C[tt + 1]){C[tt + 1] = sum + 1;}}if(tt != k){LL y = c[tt];LL sum = t.sum + abs(t.x - y);if(sum < C[tt]) {C[tt] = sum + 1;}}if(tt != 0){LL y = c[tt-1];LL sum = t.sum + abs(t.x - y);if(sum < C[tt-1]) {C[tt-1] = sum + 1;}}}}LL *p = min_element(C, C + k);cout << *p << endl; } int main(){int T;scanf("%d", &T);while(T --){for(int i = 0; i < N; i++) B[i] = C[i] = ((LL)1 << 40);scanf("%d %d %d", &n, &m, &k);for(int i = 0; i < n; i++) scanf("%lld", &a[i]);for(int i = 0; i < m; i++) scanf("%lld", &b[i]);for(int i = 0; i < k; i++) scanf("%lld", &c[i]);DFS();} }