T1题面:
一个序列长度为n,也就是一共有 n 个数,给出了一个问题:数列有几段?
段的定义是连续的相同的最长整数序列
输入第一行一个整数n,表示数的个数,接下来一行n个空格隔开的整数表示不同的数字。输出一行表示这个序列有多少段
sample input:
12
2 3 3 6 6 6 1 1 4 5 1 4
sample output:
8
数据组成
思路:
- 根据数据量构建数组,读入数组后遍历数组元素,遇到不同的就tot++
- 最终输出tot值
#include<iostream>
using namespace std;
const int N=1111;
int a[N];
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int tot=1;
int temp=a[0];
for(int i=1;i<n;i++)
{
if(temp!=a[i])
{
temp=a[i];
tot++;
}
}
printf("%d\n",tot);
return 0;
}
T2题面:
消消乐游戏规则如下:
游戏在一个包含有n 行m 列的棋盘上进行,棋盘的每个格子都有一种颜色的棋子。当一行或一列上有连续三个或更多的相同颜色的棋子时,这些棋子都被消除。当有多处可以被消除时,这些地方的棋子将同时被消除。
一个棋子可能在某一行和某一列同时被消除。
输入第一行包含两个整数n,m,表示行数和列数
接下来n行m列,每行中数字用空格隔开,每个数字代表这个位置的棋子的颜色。数字都大于0
输出n行m列,每行中数字用空格隔开,输出消除之后的棋盘。(如果一个方格中的棋子被消除,则对应的方格输出0,否则输出棋子的颜色编号。)
sample input1:
4 5
2 2 3 1 2
3 4 5 1 4
2 3 2 1 3
2 2 2 4 4
sample output1:
2 2 3 0 2
3 4 5 0 4
2 3 2 0 3
0 0 0 4 4
sample input2:
4 5
2 2 3 1 2
3 1 1 1 1
2 3 2 1 3
2 2 3 3 3
sample output2:
2 2 3 0 2
3 0 0 0 0
2 3 2 0 3
2 2 0 0 0
数据组成
思路:
- 读入给定的矩阵,存入二维数组a中,定义bool型数组b来判断哪一个位置的数需要被清除
- 清除某一行或某一列上连续三个或更多的相同颜色的棋子,可以转换为先消除某一行上连续的棋子,再消除某一列上连续的棋子。如果一个棋子可能同时在某一行某一列同时被消除,所以使用b来记录消除后的结果数据,防止出现少删除的问题。
- 将当前行中第j列和第j+1列的数据比较,如果相同则记录tot++,当该行的tot>=2的时候说明符合消除条件,然后将对应位置的值置为1;
- 注意本题最终的输出,要求行末没有多余的空格和换行
#include<iostream>
#include<cmath>
using namespace std;
int a[31][31];
bool b[31][31];
int main()
{
int n,m;
scanf("%d %d",&n,&m);
int a[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
b[i][j]=0;
}
}
//开始处理是否有相同
for(int i=0;i<n;i++)//处理行
{
int tot=0;
for(int j=0;j<m-1;j++)
{
if(a[i][j]==a[i][j+1])
tot++;
else tot=0;
if(tot>=2)
{
for(int k=j+1;k>j-tot;k--)
{
b[i][k]=1;
}
}
}
}
for(int i=0;i<m;i++)
{
int tot=0;
for(int j=0;j<n;j++)
{
if(a[j][i]==a[j+1][i])
tot++;
else tot=0;
if(tot>=2)
{
for(int k=j+1;k>j-tot;k--)
{
b[k][i]=1;
}
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m-1;j++)
{
if(b[i][j])
printf("0 ");
else
printf("%d ",a[i][j]);
}
if(b[i][m-1]) printf("0\n");
else
printf("%d\n",a[i][m-1]);
}
return 0;
}