Problem Description
题目给出两个非空整数集,请写出程序求两个集合的交集。
Input
多组输入,每组输入包括两行,第一行为集合A的元素,第二行为集合B的元素。具体参考示例输入。 每个集合元素个数不大于3000,每个元素的绝对值不大于2^32 - 1。
Output
每组输入对应一行输出,为A、B的交集,如果交集为空输出"NULL",否则交集的元素按递增顺序输出,每个元素之间用空格分割。
Example Input
1 2 3 4 5 1 5 3 6 7 1 2 4 5 3 6 7 8 9 10
Example Output
1 3 5 NULL
其中将以字符串输入的转化为数组输入的 , 不能单单判断是否为空格 , 有可能数字是一个两位数字 , 容易判断成两个一位数字
代码如下
#include<stdio.h> #include<string.h> #include<stdlib.h> int cmp(const void *a, const void *b) { return *(int *)a -*(int *)b; } char st1[800000], st2[800000]; int main() { int i, j, flag,sum,f; int a[80000], b[80000], c[80000], tp, op, top; while(gets(st1) != NULL) { tp = op = top = 0; gets(st2); int len1 = strlen(st1); int len2 = strlen(st2); sum = 0;f = 1; for(i = 0;i < len1; i++) { if(st1[i] != ' ') { if(st1[i] == '-') f = -1; else sum = sum*10+(st1[i]-'0'); } else if(st1[i] == ' '&& ((st1[i+1] >= '0' && st1[i+1] <= '9') || (st1[i+1] == '-'))) { a[op++] = sum*f; f = 1; sum = 0; } } a[op++] = sum*f; sum = 0 ; f = 1; for(i = 0; i < len2; i++) { if(st2[i] != ' ') { if(st2[i] == '-') f = -1; else sum = sum*10+(st2[i]-'0'); } else if(st2[i] == ' ' && ((st2[i+1] >= '0' && st2[i+1] <= '9') || (st2[i+1] == '-'))) { b[tp++] = sum*f; f = 1; sum = 0; } } b[tp++] = sum*f; flag = 0; for(i = 0; i < op; i++) { for(j = 0; j < tp; j++) { if(a[i] == b[j]) { flag = 1; c[top++] = a[i]; } } } if(flag == 0) printf("NULL\n"); else { qsort(&c[0], top, sizeof(c[0]), cmp); for(i = 0; i < top; i++) { printf("%d%c", c[i], i == top-1? '\n': ' '); } } } return 0; }