蒜頭君破案(集合結構體運用)

最近某地連續發生了多起盜竊案件。根據監控和路人提供的線索得知。這是一個犯罪團伙。並且還知道這個犯罪團伙中每一個人的身高、體重、年齡。警察想知道這個犯罪團伙中的每個人是不是本市的(如果本市有這個特徵的人就是本市的)。但是本市人口太多。不能一個個排查。警察急需這條信息來縮小範圍,所以警察特地找到聰明的你來幫忙解決這個棘手的問題。

輸入格式
第一行將會輸入兩個數字n(1<=n<=2*105)和m(1<=m<=104)。n代表本市的人口數目。m代表犯罪團伙的數量。
後面n行每行有3個數字代表本市每個人的身高、體重、年齡、。然後會有m行每行有3個數字代表犯罪團伙每個人的身高、體重、年齡。

輸出格式
輸出m行,每行輸出一個YES或者NO,YES代表是本市的,NO代表不是本市的。
樣例輸入:
3 2
166 50 30
178 60 23
132 40 15
167 50 30
178 60 23

樣例輸出:
NO
YES

分析:首先把身高體重打包成結構體,然後存到集合中,接着在集合利用count()判斷集合中有沒有即可
注意:
1.由於有三組數據且是結構體,所以我們要重載運算符,判斷三種情況
2.在存入集合前,我們可以在結構體聲明是就寫一個函數將輸入直接存入結構體中,這樣方便對集合進行操作,我把這個稱爲打包,然後直接調用結構體名稱存入集合中。

#include<bits/stdc++.h> 
using namespace std;
struct people{//定義結構體 
	int height ;
	int weight;
	int age;
	people(int h_,int w_,int age_)//打包 
	{ 
		height=h_;
		weight=w_;
		age=age_;
	}
	bool operator<(const people &rhs)const//重載運算符 
	{
		if(height!=rhs.height)
		{ 
		return height<rhs.height;
	    }
	    if(weight!=rhs.weight)
	    {
	    	return weight<rhs.weight;
	    }
	    else
	    return age<rhs.age;
	}
};
set<people>s; //聲明集合 
int main()
{
	int n,m,h1,w1,age1;
	cin>>n>>m;
	for(int i=0;i<n;i++){
		cin>>h1>>w1>>age1;
		s.insert(people(h1,w1,age1));//將打包好的結構體放到集合中 
	}
	for(int i=0;i<m;i++)
	{
		cin>>h1>>w1>>age1;
		if(s.count(people(h1,w1,age1)))//判斷結構體是否存在 
		cout<<"YES"<<endl;
		else
		cout<<"NO"<<endl;
	}  
	return 0;
} 

運行結果:
在這裏插入圖片描述
第二種結構體使用方式:

#include<iostream>
#include<set>
#include<cstdio>
#include<string>
using namespace std;
struct pople{
	int h;
	int w;
	string age;
	bool operator<(const pople & rhs)const
	{
		if(h!=rhs.h){
		return 	h<rhs.h;
		}
		if(w!=rhs.w){
			return w<rhs.w;
		}else{
			return age<rhs.age;
		}
	}
};
set<pople>s;
int main()
{
	string age;
	int n,h,w;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>h>>w>>age; 
	   s.insert({h,w,age});//直接打包輸入 
	}
	for(int i=0;i<m;i++)
	{ 
	cin>>h>>w>>age;
	if(s.count({h,w,age}))//打包判斷 ,記得大括號 
	printf("YES");
	else
	printf("NO");
    }
	set<pople>::iterator it;
	for(it=s.begin();it!=s.end();it++)
	cout<<it->h<<" "<<it->w<<" "<<it->age<<" "<<endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章