题目详述
题目链接:卡中心美食家
题目解析
1、在读入信息后,对其每个菜肴是否吃过需要建立一个标志数组,对每个菜肴为键,存储其包括的前置菜肴,由于前置菜肴数量不确定,所以需要用ArrayList来存储,用到 HashMap。
2、创建一个函数foodput,来具体实现对菜肴的放置,需要注意是否有互相制约,比如1是2的前置,2是1的前置,需要处理这种情况,调用栈来检查这种情况,当栈的长度超出了菜肴的总数,抛出异常,所以在主函数中需要处理异常。
程序测试
import java.util.*;
public class Main {
static int[] flag;//标志其每个菜肴是否已经吃过
static ArrayList<Integer> re=new ArrayList<Integer>();//存最后返回的ArrayList
static Stack<Integer> st=new Stack<Integer>();//用来判断前置菜肴和现在的是否为重叠的
static int n=0;
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
Map<Integer,ArrayList<Integer>> arr=new HashMap<Integer,ArrayList<Integer>>();
n= s.nextInt();
int len_fan=s.nextInt();
for(int i=0;i<len_fan;i++) {
int a=s.nextInt();
int v=s.nextInt();
if(arr.containsKey(a)) {
ArrayList<Integer> temp= new ArrayList<Integer>();
temp=arr.get(a);
temp.add(v);
arr.put(a,temp) ;//先得到目前的菜肴,加上后放回去
}else {
ArrayList<Integer> fan= new ArrayList<Integer>();
fan.add(v);
arr.put(a, fan);//没有的时候新建一个放入MAP
}
}
flag=new int[n];
for(int j=0;j<n;j++) {
flag[j]=0;
}
try {
for(int k=0;k<n;k++) {
foodput(arr,k);
}
//System.out.println(re);
int len_re=re.size();
for(int i=0;i<len_re-1;i++){
System.out.print(re.get(i));
System.out.print(",");
}
System.out.print(re.get(len_re-1)); //这里对输出的调整,最后一个没有,
}catch(Exception e) {
System.out.println("None");
}
}
public static void foodput(Map<Integer,ArrayList<Integer>> arr,int k) throws Exception {
if(flag[k]==0) {
st.push(k);
if(st.size()>n) {//出现互相制约的
throw new Exception();
}
if(arr.containsKey(k)) {
for(int j : arr.get(k)) {
foodput(arr,j); //这里需要递归调用其前置菜肴是否吃完
}
}
st.pop();
re.add(k);
flag[k]=1;
}
}
}