PAT B1065 Single Dog (25 points)

Insert picture description here
In this question, the amount of data has reached 10^5. If the double-loop violence is O(n2) time complexity, there will definitely be a test point timeout.
Therefore, you should think of space for time. For this question, you can open two hash tables, one is used to record each numbered spouse (the default is not -1), and the other is used to record whether a number is in the party attending party. Has appeared (default is false).
First enter the n pairs of spouses entered in the question into the first hash table, and then change the value of the second hash table corresponding to the m party participants entered in the question to true (indicating that they have appeared).
Finally output those who are single (that is, the value of the first hash table is -1 or the value of the spouse in the second hash table is false).

#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int spouse[100010];
bool cunzai[100010] = {
    
    false};

void init(){
    
    
	for(int i=0; i<=100010; i++){
    
    
		spouse[i] = -1;
	}
}

int main(){
    
    
	init();
	int n;
	scanf("%d", &n);
	for(int i=0; i<n; i++){
    
    
		int a, b;
		scanf("%d %d", &a, &b);
		spouse[a] = b;
		spouse[b] = a;
	}
	
	scanf("%d", &n);
	int arr[n];
	int num = 0;
	for(int i=0; i<n; i++){
    
    
		int bh;
		scanf("%d", &bh);
		cunzai[bh] = true;
		arr[num++] = bh;
	}
	int res[n];
	int r_num = 0;
	for(int i=0; i<num; i++){
    
    
		if(spouse[arr[i]]==-1 || !cunzai[spouse[arr[i]]]){
    
    
			res[r_num++] = arr[i];
		}
	}
	
	sort(res, res+r_num);
	printf("%d\n", r_num);
	for(int i=0; i<r_num; i++){
    
    
		printf("%05d", res[i]);
		if(i != r_num-1) printf(" ");
	}
	
	return 0;
}


Guess you like

Origin blog.csdn.net/weixin_45964844/article/details/113757809