栅栏密码
找规律,发现当时,顺序的第一五九个字符变成了第一二三个,两个字符相差最后一行和第一行一样
第二行有俩种情况:
- 第奇数个时下一个字符是
- 第偶数个时下一个字符是
所以跟据规律可以得出:当在第一和行时,前一个与后一个字符相差,第二行时奇数个为,第偶数个时为。
#include<bits/stdc++.h>
using namespace std;
string s;
char ans[100080];
int han = 0;
int h, len, pd1, pd2;
int check() {
if (han == 1 || han == h)return pd1 + (h - 1) * 2;
if (pd2 % 2 == 1)return pd1 + (h - han) * 2;
else return pd1 + 2 * (han - 1);
}
int main() {
cin >> h >> s;
len = s.size();
s = " " + s;
han = pd1 = pd2 = 1;
for (int i = 1; i <= len; i++) {
ans[pd1] = s[i];
pd1 = check();
pd2++;
if (pd1 > len) {
han++;
pd1 = han;
pd2 = 1;
}
}
for (int i = 1; i <= len; i++)
cout << ans[i];
return 0;
}
旅行计划
在有向无环图中求经过点最多路线的点数。
第一次想用递推,因为是有向图,所以可以得出后一个点的点数为前一个点的点数加一。但是发现有些样例的答案会小。重新读题发现第个点可能在的西边,计算顺序会少一个。
考虑动态规划: 先用数组记录入度为0的点获取最先到达的城市。再根据它的道路扩展其他城市的.
表示从1出发到i点最多路线的点数 状态转移方程:, 为 的前一个点。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+5;
int n, m, indu[N], x, y, f[N];
vector<int>g[N];
queue<int> q;
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> x >> y;
g[x].push_back(y);//存图
indu[y]++;//寻找入度为0的点作为起点
}
for (int i = 1; i <= n; i++)
if (indu[i] == 0)
q.push(i);//起点入队
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto it : g[u]) {
if (f[it] < f[u] + 1)
f[it] = f[u] + 1;//更新f[i]值
indu[it]--;
if (indu[it] == 0)
q.push(it);
}
}
for (int i = 1; i <= n; i++)
cout << f[i] + 1 << endl;//起点也算一个城市
return 0;
}商务旅行
一颗 个节点的树,所有边权为 ,给定一个路线,求路线的最小值。
考试的时候想用全源最短路求出每个点到其他点的最短距离,但是显而易见炸空间 还有不会写
定义 为 到 的最小值, 为 的深度, 为 和 的最近公共祖先。
计算公式:
#include<bits/stdc++.h>
using namespace std;
int ans, a, b, n, m, dep[1000005], fa[1000005], dp[1000005];
vector<int>edge[1005];
void dfs(int x, int father) {
fa[x] = father;
for (auto it : edge[x]) {
if (it != father) {
dep[it] = dep[x] + 1;
dfs(it, x);
}
}
}
int lca(int x, int y) {
while (dep[x] > dep[y])
x = fa[x];
while (dep[y] > dep[x])
y = fa[y];
while (x != y) {
x = fa[x];
y = fa[y];
}
return x;
}
int main() {
cin >> n;
for (int i = 1; i < n; i++) {
cin >> a >> b;
edge[a].push_back(b);
edge[b].push_back(a);
}
dfs(1, 0);
cin >> m >> b;
ans += dep[1] - dep[lca(1, b)] + dep[b] - dep[lca(1, b)];
a = b;
for (int i = 2; i <= m; i++) {
cin >> b;
ans += dep[a] - dep[lca(a, b)] + dep[b] - dep[lca(a, b)];
a = b;
}
cout << ans;
return 0;
}