今天又通宵刷题了,卡在一道大搜索上一晚上,天亮前秒了道水题,一开始以为是回溯什么的,结果发现 最多9 X 9的方格,直接暴力就行了
</pre>刷题的时候 发现了用 迭代器 遍历 vector容器的时候删除元素的一些问题</p><p><pre name="code" class="cpp">for(vector<Student_Message>::iterator it = Student.begin();it != Student.end();){
if(strcmp((*it).ID,str) == 0 || strcmp((*it).name,str) == 0){
Student.erase(it);
_count ++;
}
else
it++;
}因为erase 之后,it 自动 + 1,如果在for 里面再 + 1,就等于加了2次,肯定出错
下面说下这个水题
#include<cstdio>
#include<cctype>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<set>
#include<stack>
#include<queue>
#include<list>
using namespace std;
int n;
int mat[100][100];
bool solve(int start_x,int start_y,int L){
/*走的方向依次为 下 - 右 - 上 - 左 */
int x = start_x;
int y = start_y;
/*走下面*/
for(int i = 0 ; i < L ; i++){
int p = x * n + y;
int q = p + n;
if(x + 1 <= n && mat[p][q]){
x ++;
}
else
return 0;
}
/*走右面*/
for(int i = 0 ; i < L ; i++){
int p = x * n + y;
int q = p + 1;
if(y + 1 <= n && mat[p][q]){
y ++;
}
else
return 0;
}
/*走上面*/
for(int i = 0 ; i < L ; i++){
int p = x * n + y;
int q = p - n;
if(x - 1 >= 1 && mat[p][q]){
x --;
}
else
return 0;
}
/*走左面*/
for(int i = 0 ; i < L ; i++){
int p = x * n + y;
int q = p - 1;
if(y - 1 >= 1 && mat[p][q]){
y --;
}
else
return 0;
}
return 1;
}
int main(){
int Case = 1;
while(scanf("%d",&n) != EOF){
memset(mat,0,sizeof(mat));
int t;
int ans[10] = {0};
scanf("%d",&t);
for(int i = 0 ; i < t ; i++){
char str[10];
scanf("%s",str);
if(str[0] == 'H'){
int r,c; /*行、列*/
scanf("%d%d",&r,&c);
int x = r * n + c;
if(c + 1 <= n){
mat[x][x + 1] = 1;
mat[x + 1][x] = 1;
}
}
else if(str[0] == 'V'){
int r,c; /*行、列*/
scanf("%d%d",&c,&r);
int x = r * n + c;
if(r + 1 <= n){
mat[x][x + n] = 1;
mat[x + n][x] = 1;
}
}
}
for(int i = 1 ; i <= n ; i++) /*对每个点进行枚举*/
for(int j = 1 ; j <= n ; j++){
for(int k = 1 ; j + k <= n ; k ++){
int ok = solve(i,j,k);
if(ok){
ans[k] ++;
}
}
}
if(Case == 1) printf("Problem #%d\n",Case++);
else{
printf("\n");
printf("**********************************\n");
printf("\n");
printf("Problem #%d\n",Case++);
}
printf("\n");
int is_ok = 0;
for(int i = 1 ; i < 10 ; i++)
if(ans[i] != 0){
is_ok = 1;
printf("%d square (s) of size %d\n",ans[i],i);
}
if(is_ok == 0)
printf("No completed squares can be found.\n");
}
return 0;
}

本文分享了一次通宵刷题的经历,详细解析了一个通过暴力求解策略完成的题目,并探讨了使用C++中vector容器迭代器遍历时的注意事项。
477

被折叠的 条评论
为什么被折叠?



