T1商务旅行
做法
代码首先通过深度优先搜索(DFS)预处理出每个城镇的深度以及祖先信息(用于快速计算最近公共祖先),然后利用最近公共祖先(LCA)算法计算商人按给定顺序经过各个城镇时的最短路径总时间。 计算过程中,每两个连续城镇之间的最短路径长度通过它们的深度与它们 LCA 的深度计算得出,最后将所有连续城镇间的路径长度累加,得到总的旅行时间。 这一实现适用于城镇以树结构连接的场景(无环,任意两城镇间有唯一路径),能高效处理较大规模的输入数据(城镇数达3×10⁴3×10 4 ,经过的城镇数达3×10⁵3×10 5 )。
代码
#include<bits/stdc++.h>
using namespace std;
const int N=30005;
int h[N],fa[N][25];
vector<int>G[N];
void dfs(int x,int f) {
h[x]=h[f]+1;
fa[x][0]=f;
for(int i=1; i<=20; ++i){
fa[x][i]=fa[fa[x][i-1]][i-1];
}
for(int y:G[x]) {
if(y!=f)dfs(y,x);
}
}
int LCA(int x,int y) {//倍增
if(x==y)return x;
if(h[x]>h[y])swap(x,y);
for(int i=20; i>=0; --i) {
if(h[fa[y][i]]>=h[x]) {
y=fa[y][i];
}
}
if(x==y)return x;
for(int i=20; i>=0; --i)
if(fa[x][i]!=fa[y][i]) {
x=fa[x][i];
y=fa[y][i];
}
return fa[x][0];
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin>>n;
for(int i=1; i<n; ++i) {
int a,b;
cin>>a>>b;
G[a].push_back(b);
G[b].push_back(a);
}
dfs(1,0);
int m;
cin>>m;
long long res=0;
int rs;
cin>>rs;
for(int i=1; i<m; ++i) {
int mw;
cin>>mw;
int ac=LCA(rs,mw);
res+=h[rs]+h[mw]-2*h[ac];
rs=mw;
}
cout<<res<<"\n";
return 0;
}原因
1.码力不行;
2.对模板不熟悉
T2 无线传输
简单描述
有一串小写字母,这一串小写字母是由一子串不断copy出来的,要找出子串小写字母是什么
分析
如图,这很明显是在找最长公共前后缀,因而我们可以将图片中的第一根下划线看成当前子串,而第二根下划线看成next数组,所以
KMP启动
代码
#include<bits/stdc++.h>
using namespace std;
int n, nex[1000001], j;
char s[1000001];
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n;
cin >> s + 1;
for (int i = 1; i <= n; i++) {
if (s[j + 1] != s[i + 1] && j > 0)j = nex[j];
if (s[i + 1] == s[j + 1])
nex[i + 1] = ++j;
}
cout << n - nex[n] << endl;
return 0;
}
T3 舞蹈机器⼈
题目描述
有⼀个舞蹈机器⼈在一个⽆限⼤⼩的⼆维平⾯的原点处,这个机器⼈每次可以向⾃⼰的前⽅移动⼀个单位的⻓度,舞蹈机器⼈每移动⼀次,就必须向左或右⽅向旋转 ,最开始时,它可以选择上下左右四个⽅向中的任意⼀个作为初始⽅向。
画图,打表分析
有两种情况 {
- 当 n 偶数时
| n | 2 | 4 | 6 | … |
|---|---|---|---|---|
| ans | 4 | 9 | 16 | … |
由等差数列公式得
- 当 n 为奇数时
| n | 1 | 3 | 5 | … |
|---|---|---|---|---|
| ans | 4 | 12 | 24 | … |
由等差数列公式得
easy
代码
#include<bits/stdc++.h>
using namespace std;
int n;
int main() {
cin >> n;
if (n % 2 == 0) {
cout << (n / 2 + 1)*(n / 2 + 1);
return 0;
}
cout << (n + 3)*((n - 1) / 2 + 1);
return 0;
}原因
- 不主动动手画图打表分析
