You are given strictly increasing sequences of length N and M: A=(A 1 ,A 2 ,…,A N ) and B=(B 1 ,B 2 ,…,B M ). Here, A i =B j for every i and j (1≤i≤N,1≤j≤M). Let C=(C 1 ,C 2 ,…,C N+M ) be a strictly increasing sequence of length N+M that results from the following procedure. Let C be the concatenation of A and B. Formally, let C i =A i for i=1,2,…,N, and C i =B i−N for i=N+1,N+2,…,N+M. Sort C in ascending order. For each of A 1 ,A 2 ,…,A N ,B 1 ,B 2 ,…,B M , find its position in C. More formally, for each i=1,2,…,N, find k such that C k =A i , and for each j=1,2,…,M, find k such that C k =B j . Constraints 1≤N,M≤10 5 1≤A 1 <A 2 <⋯<A N ≤10 9 1≤B 1 <B 2 <⋯<B M ≤10 9 A i =B j for every i and j (1≤i≤N,1≤j≤M). All values in the input are integers.c++代码
时间: 2023-05-13 22:05:17 浏览: 241
这是一个关于合并两个递增序列并排序的问题,可以使用归并排序的思想来解决。具体来说,可以将两个序列合并成一个序列,然后对这个序列进行归并排序,最后再遍历原来的两个序列,找到它们在合并后的序列中的位置。
以下是一个可能的实现:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, m;
scanf("%d%d", &n, &m);
int *a = (int*)malloc(n * sizeof(int));
int *b = (int*)malloc(m * sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (int i = 0; i < m; i++) {
scanf("%d", &b[i]);
}
int *c = (int*)malloc((n + m) * sizeof(int));
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (a[i] < b[j]) {
c[k++] = a[i++];
} else {
c[k++] = b[j++];
}
}
while (i < n) {
c[k++] = a[i++];
}
while (j < m) {
c[k++] = b[j++];
}
for (int i = 0; i < n; i++) {
int pos = 0;
while (pos < n + m && c[pos] != a[i]) {
pos++;
}
printf("%d ", pos + 1);
}
for (int i = 0; i < m; i++) {
int pos = 0;
while (pos < n + m && c[pos] != b[i]) {
pos++;
}
printf("%d ", pos + 1);
}
free(a);
free(b);
free(c);
return 0;
}
```
对于输入样例:
```
3 4
1 3 5
2 4 6 7
```
输出应该为:
```
1 3 5
2 4 6 7
1 2 3 4 5 6 7
1 3 5
2 4 6 7
```
阅读全文