T1
题目解析
这道题其实就是一道字符串版最长上升子序列,看怎么连的是最长的。
错误分析
这道题我第一看上去以为这是一道暴力搜索我就往后条=跳了没有认真读题
代码
#include<bits/stdc++.h>
using namespace std;
const int N=2005;
int n, f[N], ans;
string s[N];
int main() {
cin>>n;
for(int i=1; i<=n; i++)
cin>>s[i];
for(int i=1; i<=n; i++){
f[i]=1;
for (int j=1; j<i; j++)
if (s[j]==s[i].substr(0,s[j].size()))
f[i]=max(f[j]+1,f[i]);
ans=max(f[i],ans);
}
cout<<ans;
return 0;
}
T2
题目分析
告诉我们一个棋盘大小为 n*m,再告诉我们一个起点坐标 x,y。要求我们算出到棋盘所有点最少要走几步。
从最少这个字可以看出,本题可以考虑使用 BFS 来实现。
样例数据分析 根据样例输入,我们知道棋盘大小为 3*3,开始位置为 1,1。注意,本题开始的不是零。下面我们来绘制一下到各个点需要的最少步数。我们知道不管国际象棋还是中国象棋,马都是走“日”字。也就是说,马的可能走法有 8 种。
代码
#include<bits/stdc++.h>
using namespace std;
int n, m, x, y;
bool f[405][405];
int ans[405][405];
int dx[10] = {-1,1,1,-1,-2,-2,2,2};
int dy[10] = {2,2,-2,-2,-1,1,1,-1};
struct node
{
int x, y, v;
};
void bfs(){
memset(f, 0, sizeof(f));
queue<node> q;
q.push((node){x, y, 0});
f[x][y] = 1;
while (q.empty() == 0)
{
node k = q.front();
q.pop();
for (int i = 0; i < 8; i++)
{
int newx = k.x, newy = k.y;
newx += dx[i];
newy += dy[i];
if (newx <= 0 || newx > n || newy <= 0 || newy > m)
{
continue;
}
if (f[newx][newy] == 0)
{
f[newx][newy] = 1;
ans[newx][newy] = k.v + 1;
q.push((node){newx, newy, k.v+1});
}
}
}
}
int main(){
cin>>n>>m>>x>>y;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
ans[i][j] = -1;
}
}
ans[x][y] = 0;
bfs();
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cout<<setw(5)<<ans[i][j];
}
printf("\n");
}
}