T4 P1518
1.时间复杂度:O(160100)
2.错误原因:骗分的
3.正确思路:题目中最大的地图大小就是10 * 10,农夫和牛只能向四个方向走,所以无论怎么走,都只可能出现160000种情况,接下来就只用枚举走的次数,并模拟农夫走的和牛走的即可
4.正确代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
char c[15][15];
int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, 1, 0, -1 }, a1, b1, a2, b2, cnt, cnt1, cnt2;
signed main() {
for (int i = 1; i <= 10; i++) { //输入并记录牛和农夫的坐标
for (int j = 1; j <= 10; j++) {
cin >> c[i][j];
if (c[i][j] == 'C') {
a1 = i;
b1 = j;
}
if (c[i][j] == 'F') {
a2 = i;
b2 = j;
}
}
}
while (++cnt) { //枚举走的次数
int x = a1 + dx[cnt1], y = b1 + dy[cnt1], x2 = a2 + dx[cnt2], y2 = b2 + dy[cnt2];
if (x <= 0 || x > 10 || y <= 0 || y > 10 || c[x][y] == '*') { //如果不能走了则改变方向
cnt1++;
if (cnt1 == 4) {
cnt1 = 0;
}
} else { //如果满足条件则移动一步
a1 = x;
b1 = y;
}
if (x2 <= 0 || x2 > 10 || y2 <= 0 || y2 > 10 || c[x2][y2] == '*') {
cnt2++;
if (cnt2 == 4) {
cnt2 = 0;
}
} else {
a2 = x2;
b2 = y2;
}
if (a1 == a2 && b1 == b2) { //追上了
break;
}
if (cnt == 160001) { //当走了160000后还没有追上时,就说明无解
cnt = 0;
break;
}
}
cout << cnt << endl;
return 0;
}T5 P3910
1.时间复杂度:O(n)
2.错误原因:打暴力超时了
4.正确代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, h = 1, t = 1, cnt = 1; //h是记录区间尾,t是区间头,cnt是区间和
cin >> n >> m;
while (h <= n) { //二分查找区间
if (cnt > m) { //判断是否大于总价值
cnt -= h , h++;
} else {
if (cnt == m) {
cout << "[" << h << "," << t << "]" << endl; //如果区间和等于总价值,说明找到了一个答案,输出
}
t++ , cnt += t;
}
}
return 0;
}