原:
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
using namespace std;
int main()
{
int n;
cin >> n;
vector<vector<int>> connections(n);
for (int i = 0; i < n; i++)
{
int id_from, id_to;
cin >> id_from >> id_to;
connections[i] = {id_from, id_to};
}
int target_id;
cin >> target_id;
unordered_set<int> send_mail_persons;
unordered_set<int> get_mail_persons;
unordered_map<int, int> send_mail_count;
unordered_map<int, int> get_mail_count;
int sent_mails_num = 0;
int received_mails_num = 0;
for (auto conn : connections)
{
if (conn[0] == target_id)
{
send_mail_persons.insert(conn[1]);
sent_mails_num++;
send_mail_count[conn[1]]++;
}
else if (conn[1] == target_id)
{
received_mails_num++;
get_mail_persons.insert(conn[0]);
get_mail_count[conn[0]]++;
}
}
bool is_spam = false;
for (auto person : get_mail_persons)
{
send_mail_persons.erase(person);
}
int num_unique_receivers = send_mail_persons.size();
int num_sent_mails_minus_received = sent_mails_num - received_mails_num;
if (num_unique_receivers > 5 || num_sent_mails_minus_received > 10)
{
is_spam = true;
}
else
{
for (auto entry : send_mail_count)
{
int receiver_id = entry.first;
int sent_count = entry.second;
if (get_mail_count.count(receiver_id) > 0)
{
int received_count = get_mail_count[receiver_id];
if (sent_count - received_count > 5)
{
is_spam = true;
break;
}
}
}
}
if(is_spam)
{
cout << "true ";
}
else
{
cout << "false ";
}
cout << num_unique_receivers << " " << num_sent_mails_minus_received << endl;
return 0;
}
变量优化后:
#include<iostream>
#include<vector>
#include<unordered_set>
#include<unordered_map>
using namespace std;
int main()
{
int n;
cin >> n;
vector<vector<int>> connections(n);
for(int i = 0; i < n; i++)
{
int id_from;
int id_to;
cin >> id_from >> id_to;
connections[i] = {id_from, id_to};
}
int target_id;
cin >> target_id;
unordered_set<int> to_person;
unordered_set<int> from_person;
unordered_map<int, int> to_person_count;
unordered_map<int, int> from_person_count;
int sent_num = 0;
int received_num = 0;
for(auto conn : connections)
{
if(conn[0] == target_id)
{
sent_num++;
to_person.insert(conn[1]);
to_person_count[conn[1]]++;
}
else if(conn[1] == target_id)
{
received_num++;
from_person.insert(conn[0]);
from_person_count[conn[0]]++;
}
}
bool is_spam = false;
for(auto person : from_person)
{
to_person.erase(person);
}
int num_unique_receivers = to_person.size();
int num_sent_minus_received = sent_num - received_num;
if(num_unique_receivers > 5 || num_sent_minus_received > 10)
{
is_spam = true;
}
else
{
for(auto entry : to_person_count)
{
int person_id = entry.first;
int sent_count = entry.second;
if(from_person_count.count(person_id) > 0)
{
int received_count = from_person_count[person_id];
if(sent_count - received_count > 5)
{
is_spam = true;
break;
}
}
}
}
if(is_spam)
{
cout << "true ";
}
else
{
cout << "false ";
}
cout << num_unique_receivers << " " << num_sent_minus_received << endl;
return 0;
}