码迷,mamicode.com
首页 > 其他好文 > 详细

Tsinsen_A1021. 集合运算

时间:2015-05-13 14:48:17      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:tsinsen

#include<stdio.h>
#include<string.h>

const int maxn = 2000 + 10;
int setA[maxn], setB[maxn], AB[maxn], cnt, VIS[maxn];

void init() {
	memset(setA, 0, sizeof(setA));
	memset(setB, 0, sizeof(setB));
	memset(AB, 0, sizeof(AB));
	memset(VIS, 0, sizeof(VIS));
	cnt = 0;
}

void qsort(int*a, int Left, int Right) {
	if(Left+1 >= Right) return ;
	int i = Left, j = Right-1, key = a[Left];
	while(i < j) {
		while(i < j && a[j] >= key) j--;
		a[i] = a[j];
		while(i < j && a[i] <= key) i++;
		a[j] = a[i];
	}
	a[i] = key;
	qsort(a, Left, i);
	qsort(a, i+1, Right);
}

//a 和 b 分别是集合A和集合B的元素个数 
void _print_jiao(int* A, int a, int* B, int b, int* vis) {
	int i = 0, j = 0;
	while(i < a && j < b) {
		if(A[i] == B[j]) {
			vis[i] = 1;  // vis 数组用来标记A数组 
			printf("%d ", A[i]);
			i++; j++;
		}
		if(A[i] < B[j]) i++;
		if(A[i] > B[j]) j++;
	}
	printf("\n");
}

void _print_bing(int* A, int a, int* B, int b) {
	int i = 0, j = 0; 
	while(i < a && j < b) {
		if(A[i] != B[j]) printf("%d ", (A[i] < B[j]) ? A[i++] : B[j++]);  // 下面两个语句进行合并 
	//	if(A[i] < B[j]) printf("%d ", A[i++]);
	//	if(A[i] > B[j]) printf("%d ", B[j++]);
		if(A[i] == B[j]) {
			printf("%d ", A[i]);
			i++; j++;
		}
	}
	//处理剩下的
	if(i < a) for(int k = i; k < a; k++) printf(k != (a-1) ? "%d ": "%d", A[k]);
	else for(int k = j; k < b; k++) printf(k != (b-1) ? "%d " : "%d", B[k]); 
	printf("\n");
}

void _print_yuji(int* A, int b, int* vis) {
	for(int i = 0; i < b; i++)
	if(!VIS[i]) printf(i != (b-1) ? "%d ": "%d", A[i]);
	printf("\n");
}

int main() {
	int N, M;
	while(scanf("%d", &N) != EOF) {
		init();
		for(int i = 0; i < N; i++) 
			scanf("%d", &setA[i]);
		qsort(setA, 0, N);
		scanf("%d", &M);
		for(int i = 0; i < M; i++) 
			scanf("%d", &setB[i]);
		qsort(setB, 0, M);
		_print_jiao(setA, N, setB, M, VIS);
		_print_bing(setA, N, setB, M);
		_print_yuji(setA, N, VIS);
	}
	return 0; 
}

Tsinsen_A1021. 集合运算

标签:tsinsen

原文地址:http://blog.csdn.net/czkct/article/details/45691847

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!