麻烦bobo老师帮我看下
问题描述:
这个是学校内部的一个题目,没办法放链接,问题在于有两个用例显示我超时了(没办法看具体是在什么用例上超时了),您能帮我看下如何优化嘛


相关代码:
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public int getTime(int all, int distance, int from, int to){
if(distance == 1){
return to - from;
}
HashMap<Integer, Integer> map = new HashMap<>();
int temp = from, count = 1;
while (!map.containsKey((temp + distance) % all) && !map.containsKey(to)){
map.put((temp + distance) % all ,count);
temp = (temp + distance) % all;
count ++;
}
if(map.containsKey(to)){
return map.get(to);
}else{
return -1;
}
}
public static void main(String[] args){
Main Main = new Main();
Scanner scanner = new Scanner(System.in);
int time = scanner.nextInt();
int[] res = new int[time];
for(int i = 0; i < time; i ++){
int all = scanner.nextInt();
int distance = scanner.nextInt();
int x = scanner.nextInt();
int y = scanner.nextInt();
res[i] = Main.getTime(all, distance, x, y);
}
for(int i = 0; i < time; i ++){
if(res[i] != -1 ){
System.out.println(res[i]);
}else{
System.out.println("Impossible");
}
}
}
}
源自:非比较排序
1-1 什么是计数排序
11
收起
正在回答 回答被采纳积分+1
1回答
liuyubobobo
2021-12-11 19:17:54
没有数据范围,我不能判断是否模拟可以通过,如果模拟不能通过的话,只能用数学方法解。
问题相当于求解 (x + td) % n == y 的 t,
即 td % n = (y - x + n) % n
这是一个线性同余方程,可以在网上搜一下这个关键字,查一下这个方程这么解。
想详细系统了解这个领域,应该学习数论。
继续加油!:)
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星