1. 蛇形矩阵
题目大意:给一个边长n,给出1-n^2的数字蛇形数据,例如以下
n=3
output:1 2 3 8 9 4 7 6 5
#include <stdio.h>
#include <string.h>
int main()
{
int n;
int i, j, k, row, col, trow, tcol, ttrow, ttcol;
int cnt, tcnt;
int a[100][100];
while(scanf("%d", &n)!=EOF)
{
cnt=1;
tcnt=2*n-1;
row=col=0;
for(i=n; i>0; i-=2)
{
trow=row;
tcol=col;
ttrow=row+i-1;
ttcol=col+i-1;
for(j=0; j<i; j++)
{
a[trow][tcol] = cnt;
tcol++;
cnt++; ***1***
a[ttrow][ttcol] = tcnt;
ttcol--;
tcnt++;
}
trow=row+1;
tcol=col+i-1;
ttrow=row+i-2;
ttcol=col;
for(j=0; j<i-2; j++)
{
a[trow][tcol] = cnt;
trow++;
cnt++; ***2***
a[ttrow][ttcol] = tcnt;
ttrow--;
tcnt++;
}
row++;
col++;
cnt=tcnt;
tcnt=tcnt+2*(i-2)-2;
}
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
printf("%d ", a[i][j]);
}
printf("
");
}
}
return 0;
}
主要是两部分,如代码中的1,2部分
1
如红色标记所看到的。在这个for循环里。同一时候从上方、下方运动,直到数字填完
2
如红色标记,在这个for循环里,同一时候从左方、右方运动,直到数字填完
通过1、2操作后,外层被填满,然后在内层继续填满,直到最后所有的数字所有填满。
如图:
我记得华中科技大学的复试编程题有相似的一题。
2. 很态字符串回文序列长度
题目大意:说实话,我都忘了详细怎么表述了,尽管过了一夜。大概就是给一个字符串。删除不必要的字符,求最大的回文字符长度。看到这一题。我的心里就像过电影似得。从脑中涌现各种想法。可是都貌似没啥用,后来想到一个想法就是:这样的试错的方法,可能会找到解法,可是时间效率很低。还是针对问题找解决方式。
有点说胡话了,嘿嘿。
后来想到一种方案,用的方法本质是基于动态规划的方法。
採用的是从上往下的递归方法。由于从下往上没有找到起始,所以採用了从上往下的方法。
代码:
int fun(char *str, int s, int e, int *flag)
{
int i,j;
int t1, t2;
i=s;
j=e;
if(s==e)
{
*flag=0;
return 0;
}
if((s+1) == e)
{
*flag=1;
return 1;
}
t1=fun(str, s+1, e, flag);
for(j=e-1;j>s;j--)
{
if(str[j] == str[s])
break;
}
if(j==s)
t2=t1;
else
t2=fun(str,s+1,j, flag)+1;
if(t1>t2)
return t1;
else
return t2;
}
int main()
{
char str[100+1];
int i,j, t;
int flag;
while(gets(str))
{
t= fun(str,0,strlen(str), &flag);
if(flag==0)
printf("%d
",2*t);
else
printf("%d
",2*(t-1)+1);
}
return 0;
}
flag代表是否包括回文中的单个元素。不包括对称元素,如aba中的b,flag假设是1,那么就是不包括单个元素,是偶数2*t, 否则为2*(t-1)+1。
临时先写这么多。。。