問題
數軸×有兩個點的序列A={A1,A2,…Am}和B={B1,B2,.Bn},A和Bj均爲正整數,A、B已經從小到大排好序,A、B均肯定不爲空,給定一個距離R(正整數),列出同時滿足如下條件的所有(Ai,Bj)數對
條件
1)Ai <= Bj
2)Ai,Bj 距離小於等於 R,但如果Ai 找不到R範圍內的Bj,則列出距它最近的1個Bj,當然此種情況仍然要滿足1),但如果仍然找不到,就丟棄Ai
原型
車路協同場景,一條路上發生了有很多事件(A),要通過很多路測設備(B)廣播給路上的車,需要給每個事件找到一個合適的路測設備去發送廣播消息。
輸入描述
按照人易讀的格式輸入一行數據,參見輸入樣例,其中“ABR={,}”中的每個字符都是關鍵分割符,輸入中無空格,其他均爲任意正整數,輸入A和B已經排好序,A和B的大小不超過50,正整數範圍不會超過65535。
輸出描述:
(Ai,Bj)數對序列,排列順序滿足序列中前面的Ax<=後面的Ay,前面的 Bx<=後面的By,因爲輸入A和B已經排好序,所以實際上輸出結果不用特意排序,排序不是考察點。
輸入樣例
輸入
A={1,3,5},B={2,4,6},R=1
輸出
(1,2)(3,4)(5,6)
代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void printArray(int*arr,int len){
for (int j = 0; j < len; j++)
{
if (arr[j] == 0)
{
break;
}
printf("%d ", arr[j]);
}
printf("\n");
return;
}
int getData(char* p,int * arr){
printf("%s\n",p);
if(strchr(p,'{')==NULL){
// C 庫函數 char *strrchr(const char *str, int c)
// 在參數 str 所指向的字符串中搜索最後一次出現字符 c(一個無符號字符)的位置。
p = strchr(p,'=')+1;
sscanf(p,"%d",arr);
//C 庫函數 int sscanf(const char *str, const char *format, ...)
// 從字符串讀取格式化輸入。
printArray(arr,1);
return 1;
}
p = strchr(p,'{')+1;
printf("%s\n",p);
int i = 0;
while (*p != '\0')
{
char tmp[] = "";
char *p1 = p;
int n = 0;
while(*p!=','&& *p!='\0'){
n++;
p++;
}
strncat(tmp,p1,n);
// C 庫函數 char *strncat(char *dest, const char *src, size_t n)
// 把 src 所指向的字符串追加到 dest 所指向的字符串的結尾,直到 n 字符長度爲止。
sscanf(tmp,"%d",(arr+i));
i++;
if(*p == '\0'){
break;
}
p++;
}
int arr_len = i;
printArray(arr,arr_len);
return arr_len;
}
int main()
{
int A[50] = {0};
int B[50] = {0};
int R = 0;
char str[210];
char *p = str;
scanf("%s", str);
printf("%s\n", str);
const char s[2] = "}";
p = strtok(str, s);
// C 庫函數 char *strtok(char *str, const char *delim)
// 分解字符串 str 爲一組字符串,delim 爲分隔符。
int len_A = getData(p,A);
p = strtok(NULL, s);
int len_B = getData(p,B);
p = strtok(NULL, s);
getData(p,&R);
// A[i]<=B[j]
// distance(A[i],B[j])<=R
// print all (A[i],B[j])
size_t noFind = 1;
for (int i=0;i<len_A;i++){
for(int j=0;j<len_B;j++){
if(A[i]-B[j]>0){
continue;
}
if(B[j]-A[i]<=R){
printf("(%d,%d)",A[i],B[j]);
noFind = 0;
continue;
}
if(noFind){
printf("(%d,%d)",A[i],B[j]);
}
break;
}
}
system("pause");
return 0;
}