组合字符串
使得前缀最小,我们从a中找到第一个比b大的字符串,返回之前的那一段加上b第一个字符就是字典序
时间复杂度:O(n),n为a的长度
空间复杂度:O(n),字符串长度
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
string a, b;
cin >> a >> b;
string ans;
int k = 1;
ans += a[0];
while (k < a.size() && a[k] < b[0]) ans += a[k ++ ];
ans += b[0];
cout << ans << endl;
return 0;
}
消灭老鼠
这道题考试的时候用的是存斜率的方法,这就需要考虑精度问题,比较麻烦,y总使用向量的方式比较好写,代码都给出来
斜率方法
#include <iostream>
#include <cstring>
#include <algorithm>
#include <set>
#include <cmath>
using namespace std;
typedef pair<double, double> PDD;
const int N = 1010;
const double eps = 1e-8;
struct Line
{
double k, b;
bool operator < (const Line &t) const
{
if (k != t.k) return k < t.k;
return b < t.b;
}
}l[N];
int n, ans, cnt;
int main()
{
int x, y;
cin >> n >> x >> y;
bool flag = false;
for (int i = 0; i < n; i ++ )
{
int a, b;
cin >> a >> b;
if (a == x)
{
flag = true;
continue;
}
double k = (double)(b - y) / (a - x);
double bb = b - k * a;
l[cnt ++ ] = {k, bb};
}
sort(l, l + cnt);
int ans = 0;
if (cnt >= 1) ans = 1;
for (int i = 0; i < cnt - 1; i ++ )
{
if (fabs(l[i].k - l[i + 1].k) > eps || fabs(l[i].b - l[i + 1].b) > eps)
ans ++ ;
}
cout << ans + flag << endl;
return 0;
}
向量方法
#include <iostream>
#include <cstring>
#include <algorithm>
#include <set>
#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;
}
树的DFS
预先维护DFS序,同时存储每一个结点在DFS序位置和子节点的数量去判断是否有解
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 200010;
int n, m;
vector<int> g[N];
int sz[N], p[N], q[N], id; // id表示DFS序id
void dfs(int u) // u结点数字
{
sz[u] = 1;
q[id] = u, p[u] = id;
id ++ ;
for (auto& v : g[u])
{
dfs(v);
sz[u] += sz[v];
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 2; i <= n; i ++ )
{
int x;
scanf("%d", &x);
g[x].push_back(i);
}
dfs(1);
while (m -- )
{
int u, k;
scanf("%d%d", &u, &k);
if (k > sz[u]) printf("%d\n", -1);
else
printf("%d\n", q[p[u] + k - 1]);
}
return 0;
}