CCF201812-3:CIDR合并(JAVA 快速混分 60分

2020-03-27  本文已影响0人  巨鹿lx

(此题没有充分理解题目的解法)
题目中最后,虽然给了合并的提示,但却未给出证明。也不知道,完全按照提示去合并的正确性,还要不要考虑其他的条件去合并?

所以,只写出转化标准型+排序的代码,很简单,轻轻松松60分

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;

public class CIDR合并 {
    public static class IPC implements Comparable<IPC>{
        int ip[] = new int[4];
        long v;
        int len;
        public IPC( int[] ip, long v, int len) {
            this.ip = ip;
            this.v = v;
            this.len = len;
        }
        @Override
        public int compareTo(IPC o) {
            if(this.v<o.v) return -1;
            if(this.v>o.v) return 1;
            return Integer.compare(this.len, o.len);
        }
    }
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(br.readLine());
        ArrayList<IPC> list= new ArrayList<>();
        while(n-->0) {
            String s = br.readLine();
            IPC ipc = change(s);
            list.add(ipc);
        }
        
        Collections.sort(list);
        for(IPC ip : list) {
            String res = ip.ip[0]+"."+ip.ip[1]+"."+ip.ip[2]+"."+ip.ip[3]+"/"+ip.len;
            bw.write(res+"\n");
        }
        bw.flush();
    }
    private static IPC change(String s) {
        int a[] = new int[4];
        String[] split = s.split("/");
        String left = split[0];
        int t = left.split("\\.").length;
        for(int i = t+1; i <= 4;i++) left += ".0";
        long res = 0;
        long b = 1;
        String[] split2 = left.split("\\.");
        for(int i = 3 ;i >= 0;i--) {
            a[i] = Integer.parseInt(split2[i]);
            res += b*a[i];
            b*=256;
        }
        int len = 0;
        if(s.indexOf("/")==-1) {//未标出前缀
            len = 8*t;
            left = left+"/"+len;
        }else {//标出前缀
            len = Integer.parseInt(split[1]);
            left = left + "/" +len;
        }
        return new IPC(a, res, len);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读