1、最小差值
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, a[N];
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
int res = 1e5;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
res = min(res, abs(a[i] - a[j]));
cout << res << endl;
return 0;
}
2、游戏
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int n, k, t;
queue<int> q;
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) q.push(i);
while (q.size() > 1) {
int x = q.front(); q.pop(); t++;
if (t % k && t % 10 != k) q.push(x);
}
cout << q.front() << endl;
return 0;
}
3、Crontab
4、行车路线
由题目条件 “保证答案不超过 1 0 6 10^6 106 ”,可知图中所有连续的小路长度必然小于等于 1000 1000 1000,所以点很少,考虑拆点。
数组 d i s t [ i ] [ j ] dist[i][j] dist[i][j] 表示:从起点走到点 i i i 且最后一条小路总长度为 j j j 的前提下的最短路径。
状态更新:假设从第 i i i 个点走到第 k k k 个点上权值为 w w w
- 当这条路为大路的时候: d i s t [ k , 0 ] = d i s t [ i , j ] + w dist[k, 0] = dist[i,j] + w dist[k,0]=dist[i,j]+w
- 当这条路为小路的时候: d i s t [ k , j + w ] = d i s t [ i , j ] − j 2 + ( j + w ) 2 dist[k, j + w] = dist[i, j] - j^2 + (j + w)^2 dist[k,j+w]=dist[i,j]−j2+(j+w)2
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 510, M = 200010, INF = 1e6;
int n, m;
int h[N], e[M], f[M], w[M], ne[M], idx; // f表示类型:0大道 1小道
int dist[N][1010];
bool st[N][1010];
struct Node {
int x, y, v; // x点的编号 y最后一条小路长度 v距离
bool operator<(const Node &t) const {
return v > t.v; // 因为堆是大根堆
}
};
void add(int t, int a, int b, int c) {
e[idx] = b, f[idx] = t, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
void dijkstra() {
memset(dist, 0x3f, sizeof dist); dist[1][0] = 0;
priority_queue<Node> heap; heap.push({1, 0, 0});
while (heap.size()) {
auto t = heap.top(); heap.pop();
if (st[t.x][t.y]) continue;
st[t.x][t.y] = true;
for (int i = h[t.x]; ~i; i = ne[i]) {
int x = e[i], y = t.y;
if (f[i]) { // 小路
y += w[i];
if (y <= 1000) {
if (dist[x][y] > t.v - t.y * t.y + y * y) {
dist[x][y] = t.v - t.y * t.y + y * y;
if (dist[x][y] <= INF) heap.push({x, y, dist[x][y]});
}
}
} else { // 大路
if (dist[x][0] > t.v + w[i]) {
dist[x][0] = t.v + w[i];
if (dist[x][0] <= INF) heap.push({x, 0, dist[x][0]});
}
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m--) {
int t, a, b, c; scanf("%d%d%d%d", &t, &a, &b, &c);
add(t, a, b, c), add(t, b, a, c);
}
dijkstra();
int res = INF;
for (int i = 0; i <= 1000; i++) res = min(res, dist[n][i]);
printf("%d\n", res);
return 0;
}