ACM练习题(day003)

来源:互联网 发布:淘宝三星店铺 编辑:程序博客网 时间:2024/06/06 06:53

The Triangle

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述

7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.

输入
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
输出
Your program is to write to standard output. The highest sum is written as an integer.
样例输入
573 88 1 0 2 7 4 44 5 2 6 5
样例输出
30


#include <iostream>#include <cstdio>using namespace std;int main(){int n;cin >> n;int **a=new int*[n];for (int i = 0; i < n; i++){a[i] = new int[i+1];for (int j = 0; j <= i; j++)scanf("%d", &a[i][j]);}for (int i = n - 2; i >= 0; i--){for (int j = 0; j<i + 1; j++){a[i][j] += (a[i + 1][j]>a[i + 1][j + 1]) ? a[i + 1][j] : a[i + 1][j + 1];}}cout << a[0][0]<<endl;return 0;}

擅长排列的小明

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
输入
第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出
在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例
样例输入
23 14 2
样例输出
123121314212324313234414243

#include<cstdio>  #include<cstring>#include <iostream>using namespace std;int a[10], v[10], n, m;//v数组用来判断是不是访问过,a数组存放用到的数字   void dfs(int c){if (c > m)//c>m就是数组中已经有m个数字了 输出  { for (int i = 1; i <= m; i++)printf("%d", a[i]);printf("\n");}else{for (int j = 1; j <= n; j++)//用循环找出下个哪个数字适合{   if (!v[j])//如果j适合{   a[c] = j;//c表示数组该存了第c个数了   v[j] = 1;dfs(c + 1);//递归   不能c++否则会改变c的值v[j] = 0;//恢复最后一个赋值的}}}}int main(){int t;scanf("%d", &t);while (t--){memset(v, 0, sizeof(v));scanf("%d%d", &n, &m);dfs(1);}return 0;}


原创粉丝点击