close
題目概要:
有一整數序列1<=b1<b2<b3,找出B2序列... 。B2序列=bi+bj ,i<=j ,bi+bj不可以有相等的數字。
解題方向:
直接for迴圈計算2數相加後的數字,並用個Vector記錄起來,在判斷是否有重複,當有重複就不是B2序列。
程式碼:
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; | |
import java.util.Vector; | |
import java.util.Iterator; | |
class uva11063{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
int count=1; | |
while(sc.hasNextInt()){ | |
int n=sc.nextInt(); | |
int arr[]=new int[n]; | |
for(int i=0;i<n;i++) arr[i]=sc.nextInt(); | |
boolean flag=true; | |
if(arr[0]<1) flag=false; | |
for(int i=1;i<n;i++) if(arr[i-1]>arr[i]) flag=false; //判斷讀入數字是否有由小到大排列,並不重複 | |
//bi+bj,並判斷相加後是否有重複 | |
Vector<Integer> vector=new Vector<Integer>(); | |
for(int i=0;i<n;i++){ | |
if(!flag) break; | |
for(int j=i;j<n;j++){ | |
int temp=arr[i]+arr[j]; | |
Iterator<Integer> iterator=vector.iterator(); | |
while(iterator.hasNext()){ | |
if(iterator.next()==temp) flag=false; | |
} | |
if(flag) vector.add(temp); | |
else break; | |
} | |
} | |
//Output | |
if(flag) System.out.println("Case #"+count+": It is a B2-Sequence."); | |
else System.out.println("Case #"+count+": It is not a B2-Sequence."); | |
System.out.println(""); | |
count++; | |
} | |
} | |
} | |
文章標籤
全站熱搜