A - 4308. 组合字符串
Code1 (自己的做法 -> 贪心)
#include <bits/stdc++.h>
using namespace std;
string s1, s2;
int main()
{
cin >> s1 >> s2;
string res1, res2;
res1 += s1[0], res2 += s2[0];
for (int i = 1; i < s1.length(); i++)
if (s1[i] < s2[0])
res1 += s1[i];
else break;
cout << res1 + res2;
return 0;
}
Code2 (yxc的做法 -> 枚举)
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a, b;
cin >> a >> b;
string res(20, 'z');
for (int i = 1; i <= a.size(); i ++ )
for (int j = 1; j <= b.size(); j ++ )
res = min(res, a.substr(0, i) + b.substr(0, j));
cout << res << endl;
return 0;
}
B - 4309. 消灭老鼠
Code1 (自己的做法)
#include <bits/stdc++.h>
using namespace std;
unordered_set<double> s;
int n, sx, sy;
int main()
{
int flagx = 0;
cin >> n >> sx >> sy;
for (int i = 1; i <= n; i++)
{
int x, y;
cin >> x >> y;
if (x == sx)
{
flagx = 1;
continue;
}
int xx = x - sx, yy = y - sy;
s.insert((yy * 1.0) / (xx * 1.0));
}
cout << s.size() + flagx;
return 0;
}
Code2 (yxc的做法)
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
int gcd(int a, int b){return b ? gcd(b, a % b) : a;}
int main()
{
int n, x0, y0;
cin >> n >> x0 >> y0;
set<PII> S;
while (n -- )
{
int x, y;
cin >> x >> y;
x -= x0, y -= y0;
int d = gcd(x, y);
x /= d, y /= d; // 通过最大公约数化简
if (x < 0) x = -x, y = -y; // 全都转换为正数
S.insert({x, y});
}
cout << S.size() << endl;
return 0;
}
C - 4310. 树的DFS(DFS序)
题目描述
解题思路
思路:
1.用邻接表存边。
2.dfs跑一下,记录下dfs的序列,顺便算一下以每个结点为根结点的子树结点总数(孩子节点总数+1)。
3.遍历一遍dfs序列,记下每个结点编号对应的下标,方便下面查询。
4.查询:
- 情况1:k > 以结点u为根节点的子树结点总数,输出-1;
- 情况2:否则,找到该节点对应下标(上一步保存了下来),在加上k-1,就是第k个dfs到的结点编号。
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 200020;
int n, m, sz[N], q[N], p[N], now;
vector<int> g[N];
void dfs(int u)
{
sz[u] = 1;
q[now] = u, p[u] = now, now++; // q[]存储dfs序,p[]存储某个元素在dfs序中的下标
for (auto v : g[u])
{
dfs(v);
sz[u] += sz[v];
}
}
int main()
{
cin >> n >> m;
for (int i = 2; i <= n; i++)
{
int t; cin >> t;
g[t].push_back(i);
}
dfs(1);
while (m--)
{
int u, k;
cin >> u >> k;
if (k > sz[u]) puts("-1");
else cout << q[p[u] + k - 1] << endl;
}
return 0;
}