Virtual Judge —— 数数塔 NBUT - 1083

题目

有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少?并输出最大和的路径。
在这里插入图片描述

Input

输入数据首先包括一个整数C,表示测试实例的个数,每个测试实例的第一行是一个整数N(1 <= N <= 100),表示数塔的高度,接下来用N行数字表示数塔,其中第i行有个i个整数,且所有的整数均在区间[0,99]内。

Output

对于每个测试实例,输出两行。
第一行:输入最大和。
第二行:如果最大和的路径是唯一的,输出其路径(详细格式见样例输出),否则输出” There are several solutions!”

Sample Input

2
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
3
1
1 1
1 1 1

Sample Output

30
(0, 0) -> (1, 0) -> (2, 0) -> (3, 1) -> (4, 1)
3
There are several solutions!

Hint

不要用cin 和 cout,否则会超时(⊙_⊙)

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
    int a[101][101],d[101][101],map[101][101];
    int n,m;
    while(~scanf("%d",&n))
    {
        while(n--)
        {
            memset(map,0,sizeof(map));
            scanf("%d",&m);
            for(int i=0;i<m;i++)
          		for(int j=0;j<i+1;j++)
          		{
            	    scanf("%d",&d[i][j]);
                	a[i][j] = d[i][j];
          		}
            for(int i=m-2;i>=0;i--)
	   		    for(int j=0;j<=i;j++)
				   a[i][j]+=max(a[i+1][j],a[i+1][j+1]);
            printf("%d\n",a[0][0]);
            int i=0,j=0,c=0;
            while(j < m-1 && i < m-1)
            {
                if((a[i][j]-d[i][j]) == a[i+1][j]&&(a[i][j]-d[i][j]) == a[i+1][j+1])
                    {
                        c = 1;
                        break;
                    }
                else
                {
                    if(a[i+1][j] < a[i+1][j+1]) j++;
                }
                i++;
                map[i][j] = 1;
            }
            if(c) printf("There are several solutions!\n");
            else
            {
                printf("(0, 0)");
                j = 0;
                for(int i=1;i<m;i++)
                {
                    if(map[i][j] == 1) printf(" -> (%d, %d)",i,j);
                    else printf(" -> (%d, %d)",i,++j);
                }
                 printf("\n");
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43336281/article/details/88342543