299. Triangle
Memory limit: 65536 kilobytes
output: standard
It is well known that three segments can make a triangle if and only if the sum of lengths of any two of them is strictly greater than the length of the third one. Professor Vasechkin has N segments. He asked you, if you could find at least one set of three segments among them which can be used by professor to make a triangle.
sample input | sample output |
7 1 2 6 4 8 100 73 | 8 4 6 |
import java.lang.reflect.Array; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] arg){ Scanner cin=new Scanner(System.in); int n=cin.nextInt(); BigInteger[] a = new BigInteger[1005]; for(int i=0;i<n;i++) { a[i] = cin.nextBigInteger(); } Arrays.sort(a,0,n); boolean f=true; for(int i=0;i+2<n;i++){ if(a[i].add(a[i+1]).compareTo(a[i+2])==1){ System.out.println(a[i]+" "+a[i+1]+" "+a[i+2]); f=false; break; } } if(f==true){ System.out.println("0 0 0"); } } }
從大到小的
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
BigInteger a[]={BigInteger.valueOf(5), BigInteger.valueOf(5), BigInteger.valueOf(7),
BigInteger.valueOf(2), BigInteger.valueOf(0)};
Comparator cmp = new MyComparator();
Arrays.sort(a, cmp);
System.out.println(Arrays.toString(a));
}
static class MyComparator implements Comparator<BigInteger>//從大到小排序
{
@Override
public int compare(BigInteger o1, BigInteger o2) {
if(o1.compareTo(o2)<=0)
return 1;
else if(o1.compareTo(o2)==0)
return 0;
else
return -1;
}
}
}