CCF 2018年12月 第三题 CIDR合并



import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Main{
	public static List list = new ArrayList();
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		scanner.nextLine();
		list.add(convertToBinaryIp(scanner.nextLine()));
		n--;
		boolean flag = false;
		while(n-->0){
			Ip ip = convertToBinaryIp(scanner.nextLine());
			for(int i = 0 ; i < list.size(); i++){
				if(ip.ip.compareTo(list.get(i).ip) == -1 || (ip.ip.compareTo(list.get(i).ip) == 0 && ip.length =list.size()){
				break;
			}
			if(isUnion(list.get(i), list.get(j))){
				list.get(i).length--;
				list.remove(j);
				if(i==0){
					i--;
				}
				else {
					i = i-2;
				}
			}
		}
		
		
		for(int i = 0; i < list.size();i++){
			char[] ip = list.get(i).ip.toCharArray();
			int tempIp[] = new int[5];
			int j = 0;
			int sum = 0;
			while(j= b.length){
			return false;
		}
		
		return a.ip.substring(0,a.length).equals(b.ip.substring(0, a.length));
		
	}
	
	public static boolean isUnion(Ip a, Ip b){
		if(a.length != b.length){
			return false;
		}
		

		return a.ip.substring(0, a.length-1).equals(b.ip.substring(0, b.length-1)) && a.ip.substring(a.length,a.length) != b.ip.substring(a.length,a.length);
		
	}
	
	public static Ip convertToBinaryIp( String input) {
		String result = new String();
		int length = 0;
		String temp[] = input.split("/")[0].split("\\.");
		for(int i = 0; i< temp.length; i++){
			int tempVal = Integer.parseInt(temp[i]);
			for(int j = 7; j>=0; j--){
				if(tempVal>=Math.pow(2, j)){
					result +="1";
					tempVal-=Math.pow(2, j);
				}
				else {
					result +="0";
				}
			}
		}
		if(input.split("/").length == 2){
			length = Integer.parseInt(input.split("/")[1]);
		}
		else {
			length = 8* temp.length;
		}
		
		for(int i = temp.length; i < 4; i++){
			result +="00000000";
		}
		
		return new Ip(result, length);
	}
	
	
	public static class Ip{
		public String ip;
		public int length;
		
		public Ip(String ip, int length){
			this.ip = ip;
			this.length = length;
		}
	}

}

 

你可能感兴趣的:(CCF 2018年12月 第三题 CIDR合并)