題目概要:
Ex :
5 | 3 | 2 | 7 | 9 |
1 | 7 | 4 | 2 | 4 |
5 | 3 | 2 | 4 | 6 |
1 | 3 | 4 | 5 | 1 |
1 | 4 | 5 | 6 | 3 |
計算出(各邊裡數字的總和):
1 .5+3+2+7+9+1+4+5+6+1+1+1+3=63
2. 7+4+2+3+4+3+4+5=32
3. 2
解題方向:
最外圍總和-裡面總和。 Ex 如上表 紅字-(藍字+黑字)
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
class uva11470{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
int n; | |
int cases=1; | |
while(sc.hasNextInt() && (n=sc.nextInt())!=0){ | |
//初始化陣列。 | |
int arr[][]=new int[n][n]; | |
for(int i=0;i<n;i++){ | |
for(int j=0;j<n;j++){ | |
arr[i][j]=sc.nextInt(); | |
} | |
} | |
int s=0; //最小邊界。 | |
int e=n; //最大邊界 | |
System.out.print("Case "+cases+":"); | |
while(s<=e){ | |
int out=0,in=0; | |
//最外圍總和。 | |
for(int i=s;i<e;i++){ | |
for(int j=s;j<e;j++){ | |
out=out+arr[i][j]; | |
} | |
} | |
//內圈總和。 | |
for(int i=s+1;i<e-1;i++){ | |
for(int j=s+1;j<e-1;j++){ | |
in=in+arr[i][j]; | |
} | |
} | |
// Output | |
if((out-in)!=0) System.out.print(" "+(out-in)); | |
s++; | |
e--; | |
} | |
System.out.println(""); | |
cases++; | |
} | |
} | |
} |
文章標籤
全站熱搜