7-29课程解析+总结
题目解析+总结
T638908
有一个的网格如图所示: 你要给这个矩阵做一下操作:
- 读入一个整数,找到网格中的这个整数对应的坐标,将此标记。
- 判断矩阵的每行、每列、每条对角线是否标记
- 重复第一个步骤
请问,至少需要多少次操作,才能使矩阵的每行、每列、每条对角线全部被标记?
分析
直接取一个的矩阵,坐标如下:
| 行和列 | 1 | 2 | 3 |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 |
我们可以发现一个规律(当矩阵上的数为): 坐标的第一个数(): 坐标的第二个数()(若不能被整除): 坐标的第二个数()(若能被整除): 判断是否是对角线:满足或
推导出公式后,可以用数组和变量存储这些信息,也方便判断是否满足条件。
H[x]++,L[y]++;
if(x == y) dj1++;
if(x + y == n+1) dj2++;
if(H[x] == n || L[y] == n || dj1 == n || dj2 == n){
cout<<HH<<endl;
return 0;
}代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,t,dj1 = 0,dj2 = 0,HH = 0,H[2005],L[2005];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n>>t;
while(t--){
HH++;
int a;
cin>>a;
int x = ceil(a*1.00/n),y;
if(a % n == 0) y = n;
else y = a % n;
H[x]++,L[y]++;
if(x == y) dj1++;
if(x + y == n+1) dj2++;
if(H[x] == n || L[y] == n || dj1 == n || dj2 == n){
cout<<HH<<endl;
return 0;
}
}
cout<<-1<<endl;
return 0;
}总结+错误原因
数学推导公式 + “八皇后” 错因:公式推导错误
T638280
有一个只有.、#、S的网格。其中,S表示起点,.表示空地,#表示障碍物。
你现在在起点处,从起点开始,不断走到相邻的格子,最终回到起点,如果走过了及以上个格子🕊,输出Yes。如果怎样走都不能满足条件,输出No。
分析
因为数据量太大,所以我们需要使用vector,建议使用广度优先搜索。 先输入一个字符,将vis标记,并判断是否是起点,要是不习惯下标从开始的话,可以先随便存入一个整数。
for (int i = 1; i <= n; i++){
vis[i].push_back(1);
for (int j = 1; j <= m; j++){
cin >> c;
if (c == '#') vis[i].push_back(1);
else if (c == 'S') sx = i, sy = j, vis[i].push_back(1);
else vis[i].push_back(0);
}
}最后,直接开始广搜就可以了,注意要将队列清空。
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e6 + 10;
int n, m, sx, sy;
int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
char c;
struct node{
int x, y;
};
queue<node> q;
vector<int>vis[N];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++){
vis[i].push_back(0);
for (int j = 1; j <= m; j++){
cin >> c;
if (c == '#') vis[i].push_back(1);
else if (c == 'S') sx = i, sy = j, vis[i].push_back(1);
else vis[i].push_back(0);
}
}
for (int i = 0; i < 4; i++){
int x = sx + dx[i], y = sy + dy[i];
if (x < 1 || x > n || y < 1 || y > m) continue;
if (!vis[x][y]){
vis[x][y] = 1;
while (q.size()) q.pop();
q.push({x, y});
while (q.size()){
node k = q.front();
q.pop();
for (int j = 0; j < 4; j++){
int xx = k.x + dx[j], yy = k.y + dy[j];
if (xx < 1 || xx > n || yy < 1 || yy > m || vis[xx][yy]) continue;
vis[xx][yy] = 1;
if(xx==sx+1&&yy==sy || xx==sx-1&&yy==sy || xx==sx&&yy==sy+1 || xx==sx&&yy==sy-1){
cout << "Yes" << endl;
return 0;
}
q.push({xx, yy});
}
}
}
}
cout << "No" << endl;
return 0;
}总结
广度优先搜索