![](/img/trans.png)
[英]Getting data from edittext when switchbox is enabled in Android using Java
[英]Switchbox routing with stack (java language)
我一直在从事有关Java中堆栈的大学作业,但似乎找不到该作业的帮助。 这是关于配电箱路由的,我需要使用堆栈进行此分配。 作业定于明天到期,但由于我只在寻找解决方案,而不是成绩,因此无需着急回答。 由于问题不是用英语写的,所以我将给出简短的解释。
配电箱包含4n针,配电箱的每一侧都有n针。 仅当连接一对引脚的线中的任何一条都不相交时,开关盒才可布线。 输入将是成对的连接引脚号。
我发现了一些可能的解决方案,但无法理解:1.该问题可以通过与括号匹配的算法类似的算法来解决。2.将引脚号放入堆栈和数组中并进行比较(这是最令人困惑的一个)
到目前为止,我的代码(尝试第二种算法):
import java.util.Scanner;
import java.util.Stack;
public class Tester {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int cases=sc.nextInt();
for(int i=0;i<cases;i++){
int pin=sc.nextInt();
SwitchBox box=new SwitchBox(pin);
for(int j=0;j<pin*4;j++){
box.add(sc.nextInt());
}
boolean res=box.isRoutable();
if(res){
System.out.println("routable");
}
else{
System.out.println("not routable");
}
}
}
static class SwitchBox{
Stack<Integer> pins;
int[] pairs;
int[] comparator;
public SwitchBox(int pin){
this.pins=new Stack<Integer>();
this.pairs=new int[(pin*4)];
this.comparator=new int[this.pairs.length];
}
public boolean isRoutable(){
Stack<Integer> s=new Stack<Integer>();
for(int i=0;i<pairs.length;i++){
pairs[i]=pins.peek();
s.push(pins.pop());
}
for(int i=pairs.length-1;i>=0;i--){
if(pairs[i]!=s.pop()){
return true;
}
}
return false;
}
public void add(int pinNum){
if(pins.isEmpty()){
pins.push(pinNum);
}
else{
Stack<Integer> temp=new Stack<Integer>();
int top=(int)pins.peek();
while(top>pinNum){
temp.push(pins.pop());
if(pins.isEmpty()) top=pinNum;
else top=(int)pins.peek();
}
pins.push(pinNum);
while(!temp.isEmpty()){
pins.push(temp.pop());
}
}
}
}
}
在您的add
方法中, else
块是错误的。 我无法理解您想做什么,但您需要做下一件事
public void add(int pinNum) {
if (pins.isEmpty()) {
pins.push(pinNum);
} else {
Integer last = pins.peek();
if (last == pinNum) {
pins.pop();
} else {
pins.push(pinNum);
}
}
}
之后, isRoutable
方法只需要检查pins
堆栈即可。 如果为空,则一切正常。 否则有相交的线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.