招行卡中心编程题_卡中心美食家

题目详述

题目链接:卡中心美食家

题目解析

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;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值