2016.4.3腾讯笔试编程题
2016-04-04 14:49
246 查看
1. 蛇形矩阵
题目大意:给一个边长n,给出1-n^2的数字蛇形数据,如下n=3
⎡⎣⎢187296345⎤⎦⎥
\begin{bmatrix}
1 & 2 & 3 \\
8 & 9 & 4 \\
7 & 6 & 5
\end{bmatrix}
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("\n"); } } return 0; }
主要是两部分,如代码中的1,2部分
1
如红色标记所示,在这个for循环里,同时从上方、下方运动,直到数字填完
2
如红色标记,在这个for循环里,同时从左方、右方运动,直到数字填完
通过1、2操作后,外层被填满,然后在内层继续填满,直到最后所有的数字全部填满。如图:
我记得华中科技大学的复试编程题有类似的一题。
2. 非常态字符串回文序列长度
题目大意:说实话,我都忘了具体怎么表述了,虽然过了一夜。大概就是给一个字符串,删除不必要的字符,求最大的回文字符长度。看到这一题,我的心里就像过电影似得,从脑中涌现各种想法,但是都貌似没啥用,后来想到一个想法就是:这种试错的方法,可能会找到解法,但是时间效率很低。还是针对问题找解决方案。有点说胡话了,嘿嘿。后来想到一种方案,用的方法本质是基于动态规划的方法。
采用的是从上往下的递归方法,因为从下往上没有找到起始,所以采用了从上往下的方法。
f(s,e)=⎧⎩⎨0,1,max(f(s,e)+1,f(s+1,e)),if (s==e) if (s+1==e) others
f(s,e) =
\begin{cases}
0, & \text{if $(s==e)$ } \\
1, & \text{if $(s+1 ==e)$ } \\
max(f(s,e)+1, f(s+1,e)), & \text{others}
\end{cases}
代码:
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\n",2*t); else printf("%d\n",2*(t-1)+1); } return 0; }
flag代表是否包含回文中的单个元素,不包含对称元素,如aba中的b,flag如果是1,那么就是不包含单个元素,是偶数2*t, 否则为2*(t-1)+1。
暂时先写这么多。。。
相关文章推荐
- [转载]C++中类的组合
- Manage Code 托管代码
- matlab simulink 使用总结
- spring security+mybatis+springMVC构建一个简单的项目
- C# 中类的成员有哪些?
- eclipse配置;eclipse和jdk对应关系
- 【Java集合源码剖析】LinkedList源码剖析
- java.lang.NoSuchMethodException: onClickCallback []
- Java基础笔试题
- mac下使用github
- Struts中action添加用户后客户端弹出对话框
- ubuntu下eclipse创建启动栏图标 (或ubuntu下创建图标)
- java语言运作模式理解图
- C/C++—— C++中定义虚析构函数的原因
- 【java集合框架源码剖析系列】java源码剖析之HashSet
- 【java集合框架源码剖析系列】java源码剖析之HashSet
- gcc编译链接C代码
- C语言一些关于位操作符的小练习
- C++ 构造函数
- C#中的继承举例