红黑树(set,map)算法题
1.英语作文
P2786 英语1(eng1)- 英语作文 - 洛谷
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<map>
using namespace std;
typedef long long LL;
int n, p;
LL sum = 0;
map<string, int> mp;//高级词汇,含金量
bool check(char s)
{
if (s >= '0' && s <= '9' || s >= 'a' && s <= 'z' || s >= 'A' && s <= 'Z')
{
return true;
}
else
return false;
}
int main()
{
cin >> n >> p;
for (int i = 1; i <= n; i++)
{
string st; int x; cin >> st >> x;
mp[st] = x;//自动创建一个key为st的插入到mp中
}
char s;
string res = "";
while (scanf("%c", &s) != EOF)//这里的EOF表示结束符,这里使用scanf的话可以把空格视作一个分隔符,而cin则会自动跳过
{
if (check(s))res += s;
else
{
sum = (sum + mp[res]) % p;
res = "";
}
}
cout << sum << endl;
return 0;
}
while (scanf("%c", &s) != EOF)//这里的EOF表示结束符,这里使用scanf的话可以把空格视作一个分隔符,而cin则会自动跳过空格
mp[t] = x;开辟一个key值为t的空间,映射x
2.P2234 [HNOI2002] 营业额统计 - 洛谷
#include<iostream>
#include<set>
#include<math.h>
using namespace std;
int n,sum = 0;
set<int> st;
int INF = 1e7;//极大值
int main()
{
cin >> n;
int x; cin >> x;
sum += x;
st.insert(x);
st.insert(INF); st.insert(-INF);
for (int i = 2; i <= n; i++)
{
int y; cin >> y;
auto r = st.lower_bound(y);//返回的是一个迭代器
auto l = r;
l--;
if (*r == y)continue;
else
{
sum += min(abs(*r - y), abs(y - *l));
}
st.insert(y);
}
cout << sum << endl;
return 0;
}
左右护法:鉴于绝对值取小,那么只要采用左右护法可以避免,取迭代空
3.记录详情 - 洛谷 | 计算机科学教育新生态
#include<iostream>
#include<set>
#include<math.h>
using namespace std;
typedef long long LL;
const LL INF = 1e10;
LL op;
set<LL> st;
int main()
{
cin >> op;
//左右护法
st.insert(-INF);
st.insert(INF);
while (op--)
{
int x, y;
cin >> x;
if (x == 1)
{
cin >> y;
if (st.count(y))
{
cout << "Already Exist" << endl;
}else
st.insert(y);
}
else
{
cin >> y;
auto r = st.lower_bound(y);
auto l = r;
l--;
if (abs(*r - y) >= abs(y - *l))
{
cout << *l << endl;
st.erase(l);
}
else
{
if (st.size()==2)
{
cout << "Empty" << endl;
}
else
{
cout << *r << endl;
st.erase(r);
}
}
}
}
return 0;
}