package huawei; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; public class Q0003_serverArrange { /* * 0:无服务器 * 1:有服务器 * -1:服务器宕机 * * 初始服务器:以 0位初始,50为间隔, * 增添服务器:以25为初始,若加500不溢出,则加500,否则加50 */ public static void main(String[] args) throws IOException { System.setIn(new BufferedInputStream(new FileInputStream("resource/huawei0003.txt"))); Scanner sc = new Scanner(System.in); String[] command = sc.nextLine().split(":"); int[] servers = new int[1000]; arrageServer(servers, 20, false); int index; String[] temp; switch (command[0]) { case "1": temp = command[1].split("_"); index = Integer.parseInt(temp[temp.length - 1]); System.out.println((index - 1) * 50); break; case "2": index = getHash(command[1]); System.out.println(findServer(servers, index)); break; case "3": //处理宕机服务器 temp = command[1].split(";"); String[] shutdowns = temp[0].split(","); for (int i = 0; i < shutdowns.length; i++) { String[] curTemp = shutdowns[i].split("_"); shutdownServer(servers, Integer.parseInt(curTemp[curTemp.length - 1])); } index = getHash(temp[temp.length - 1]); System.out.println(findServer(servers, index)); break; case "4": temp = command[1].split("_"); index = Integer.parseInt(temp[temp.length - 1]); System.out.println((index - 1) * 50 + 25); break; case "5": temp = command[1].split(";"); String[] addServers = temp[0].split("_"); arrageServer(servers, Integer.parseInt(addServers[addServers.length - 1]), true); index = getHash(temp[1]); System.out.println(findServer(servers, index)); break; } } // 计算token的哈希值 public static int getHash(String str) { int res = 0; for (int i = 0; i < str.length(); i++) { res += (int) str.charAt(i); res %= 999; } return res; } // 查找分配服务器位置 public static int findServer(int[] arr, int index) { if (arr[index] != 0) return index; while (true) { index = (index + 1) % arr.length; if (arr[index] == 1) return index; } } // 设置宕机服务器 public static void shutdownServer(int[] arr, int index) { arr[(index - 1) * 50 + 0] = -1; } // 安排服务器 public static void arrageServer(int[] arr, int num, boolean isAdd) { int gap = 50; if (!isAdd) { //首次添加 for (int i = 0; i < num; i++) { arr[i * gap] = 1; } } else { int index = 25; arr[index] = 1; for (int i = 1; i < num; i++) { index = index + 500 > 1000 ? index - 450 : index + 500; arr[index] = 1; } } } }
点赞 评论
牛客网
牛客企业服务