seansie's blog

Zerojudge a541 題解

題解-基本版

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n;
	set<string> st;
	string s;
	cin>>n;
	for(int i=0;i<n;i++) {
		cin>>s;
		st.insert(s);
	}
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>s;
		cout<<((st.find(s)==st.end())?"no\n":"yes\n");
		st.insert(s);
	}
}

精益求精優化版


#include<bits/stdc++.h>
using namespace std;
int main(){
	int n,m;
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	unordered_set<string> st;
	string s;
	cin>>n;
	st.reserve(n);
	for(int i=0;i<n;i++) {
		cin>>s;
		st.insert(s);
	}
	cin>>m;
	st.reserve(n+m);
	for(int i=0;i<m;i++){
		cin>>s;
		bool flag=st.find(s)==st.end();
		cout<<((flag)?"no\n":"yes\n");
		if(flag)st.insert(s);
	}
}

1. ios_base::sync_with_stdio(false); cin.tie(nullptr);

這兩個語句旨在優化 C++ 中的輸入輸出 (I/O) 操作。

  • ios_base::sync_with_stdio(false);:此語句會關閉 C++ 流與標準輸入輸出 (stdio) 的同步。默認情況下,C++ 流與 stdio 同步,這意味著每次進行 I/O 操作時,C++ 流都會等待 stdio 緩衝區刷新。關閉同步可以提高 I/O 操作的性能,尤其是當涉及大量的 I/O 操作時。
  • cin.tie(nullptr);:此語句會將 C++ 輸入流 (cin) 與 C++ 輸出流 (cout) 解耦。默認情況下,cincout 是綁定的,這意味著每次進行 cout 操作時,cin 都會被刷新。解耦 cincout 可以提高 I/O 操作的性能,尤其是當 cout 操作頻繁發生時。

2. unordered_set<string> st;unordered

unordered_set 是 C++ 標準庫中提供的一種無序集合容器。unordered_set 使用哈希表來存儲元素,因此具有快速的插入、查找和刪除操作。unordered 關鍵字是 unordered_set 的模板參數,它指定瞭如何對元素進行哈希。默認情況下,unordered_set 使用默認的哈希函數來對元素進行哈希。

在某些情況下,使用自定義哈希函數可以提高 unordered_set 的性能。例如,如果您的元素是字符串,則可以使用字符串專用哈希函數來提高查找性能。

3. st.reserve(n);

reserve()unordered_set 類別提供的一個成員函數。它會通知 unordered_set 為預計要插入的元素分配足夠的內存。這可以防止 unordered_set 在插入元素時需要重新分配內存,從而提高插入性能。

在某些情況下,在插入大量元素之前調用 reserve() 可以提高 unordered_set 的性能。但是,如果預計要插入的元素數量不確定,則不應調用 reserve()。這是因為 reserve() 會分配內存,即使最終未使用該內存也會浪費內存。