Hansel and Gretel

来源:互联网 发布:移动测速软件 编辑:程序博客网 时间:2024/06/05 10:35

Long time ago, there lived Hansel and Gretel. And a strange witch took Hansel to the deep forest to get rid of him. Smart Hansel abandoned scraps of bread that he’d got little by little on the way to the forest. But the problem is that the scraps of bread scattered here and there by the similar scraps by other mountaineers is making hard for Gretel to follow. At this time, a fairy of the forest appears to tell her how to find the way. ‘Move to where you can find as many scraps of bread as you can.’
Following to her advice, Gretel plans to use the route where she can find as many scraps of bread as she can from the departure to the destination. There is one condition that she is allowed to move up or left only along the mountain to the destination.



Create a program that she can find the way as the fairy advised.

Time limit: 1 second (java: 2 seconds)

Input format


Several test cases can be included in the inputs. T, the number of cases is given in the first row of the inputs. After that, the test cases as many as T (T ≤ 30) are given in a row.
N, the size of the forest is given in the first row of each test case. The forest is always the square shape of N×N size. The information of the forest is given by being separated as spaces over the lines of the number of N from the second row. In case a scrap of bread is in the corresponding cell, it is 1, and in case a scrap of bread is not in the corresponding cell, it is 0.

Output format

Output the number of bread when they take bread as much as they can from the departure on the first row of each test case to the destination.

Example of Input

2
5
0 1 0 0 1
0 0 1 0 0
1 0 1 1 0
1 1 0 1 0
1 0 0 0 1
10
1 0 0 1 0 1 0 0 1 0
1 1 1 0 1 1 1 1 0 0
0 0 0 1 1 0 1 0 0 0
0 1 1 1 0 0 0 0 1 0
1 0 1 1 0 0 1 0 1 0
0 0 1 1 1 0 1 0 1 0
1 1 0 0 0 0 1 0 1 0
0 1 0 1 1 1 0 0 0 0
1 0 1 1 0 1 0 0 1 0
0 0 0 1 1 0 1 0 1 0

Example of Output

6
14 


Hint

Map[i][j] = max{ Map[i][j-1]+Map[i][j], Map[i-1][j]+Map[i][j] }

Do calculation when scanf.

#include <stdio.h>#define   MAX(a,b)  (a>b?a:b)int data[1001][1001];int F[1001][1001];int main(void){int tc, T;int N,i,j;// freopen("input.txt", "r", stdin);setbuf(stdout, NULL);scanf("%d", &T);for(tc = 0; tc < T; tc++){scanf("%d", &N);for(i=0;i<N;i++){for(j=0;j<N;j++){F[i][j] = 0;scanf("%d", &data[i][j]);}}if(data[0][0])F[0][0] = 1;for(i=1;i<N;i++){F[i][0] = F[i-1][0]+data[i][0];F[0][i] = F[0][i-1]+data[0][i];}for(i=1;i<N;i++)for(j=1;j<N;j++){F[i][j] = MAX(F[i-1][j],F[i][j-1])+data[i][j];}printf("%d\n",F[N-1][N-1]);/***********************************  Implement your algorithm here. ************************************/// Print the answer to standard output(screen).}return 0;}



0 0
原创粉丝点击