今天又来打卡,今天写了5道题,都比较容易,基本都是秒了,但是看题解的时候还是有收获,
写了P1551,P1536,P370,P3405,P5250。
首先是P1551和P1536这个我都是用并查集写的很容易,直接上代码:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int n, m, p;
int f[5004];
void Init()
{
for (int i = 1; i <= n; i++)
f[i] = i;
}
int find(int x)
{
while (f[x] != x)
{
x = f[x];
}
return x;
}
int main()
{
cin >> n >> m >> p;
Init();
for (int i = 1; i <= m; i++)
{
int M, N;
cin >> M >> N;
if (find(M) == find(N))
{
continue;
}
while (f[M] != M)
{
M = f[M];
}
f[M] = N;
}
for (int i = 1; i <= p; i++)
{
int p1, p2;
cin >> p1 >> p2;
if (find(p1) == find(p2))
{
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int n, m;
int f[5004];
void Init()
{
for (int i = 1; i <= n; i++)
f[i] = i;
}
int find(int x)
{
while (f[x] != x)
{
x = f[x];
}
return x;
}
int main()
{
while (cin >> n && n != 0)
{
cin >> m;
Init();
for (int i = 1; i <= m; i++)
{
int x1, x2;
cin >> x1 >> x2;
if (find(x1) == find(x2))
continue;
while (f[x1] != x1)
x1 = f[x1];
f[x1] = x2;
}
int ans = 0;
for (int i = 1; i <= n; i++)
{
if (f[i] == i)
{
ans++;
}
}
cout << ans-1 << endl;
}
return 0;
}
然后是P3370,一个模板题,直接用map就行了,就不多说了:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <map>
#include <string.h>
using namespace std;
map <string, int> m;
int N;
int main()
{
cin >> N;
for (int i = 1; i <= N; i++)
{
string a;
cin >> a;
if (m.find(a) == m.end())
{
m[a] = 1;
}
}
cout << m.size() << endl;
return 0;
}
后面两道题得重点说说,P3405这个里面有个很重要的地方就是hash离散化,把字符转化成数字,然后就是直接通过m[x1][x2]和m[x2][x1]来统计:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <map>
#include <string.h>
using namespace std;
map <int, int> m[100005];
int N;
int main()
{
int ans = 0;
cin >> N;
for (int i = 1; i <= N; i++)
{
string a, b;
cin >> a >> b;
int x1 = (a[0] - 'A') * 26 + a[1] - 'A';
int x2 = (b[0] - 'A') * 26 + b[1] - 'A';
ans += m[x2][x1];
if (x1 == x2)
ans -= m[x1][x2];
m[x1][x2]++;
}
cout << ans << endl;
return 0;
}
最后一题P5250,这个是收获最多的一个是熟悉了set中的函数,比如:lower_bound和upper_bound,还知道了insert回返回一个pair,其中pair->first是插入的数据的迭代器,pair->second是bool类型看是否插入成功:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
using namespace std;
int n;
set <int> trees;
int op, len;
int main()
{
cin >> n;
while (n--)
{
cin >> op >> len;
if (op == 1)
{
if (!trees.insert(len).second)
cout << "Already Exist" << endl;
}
else {
if (trees.empty())
cout << "Empty" << endl;
else {
if (trees.find(len) != trees.end())
{
cout << len << endl;
trees.erase(len);
}
else {
set <int>::iterator it, it1;
it = it1 = trees.lower_bound(len);
if (it == trees.begin())
{
cout << *it << endl;
trees.erase(it);
}
else if (it == trees.end())
{
cout << *(--it) << endl;
trees.erase(it);
}
else if (*it - len < len - *(--it1))
{
cout << *it << endl;
trees.erase(it);
}
else {
it--;
cout << *it << endl;
trees.erase(it);
}
}
}
}
}
return 0;
}
继续努力!!!