2022.03.05时间复杂度

这篇博客探讨了如何使用栈来模拟编程中的循环结构,并处理变量和时间复杂度。文章介绍了当遇到变量冲突、无法进入循环或错误时的处理方法,并提供了具体的代码实现,用于判断给定的循环条件是否满足。同时,注意到了输入处理的细节,如行末的回车符可能对后续输入的影响。最后,通过实例展示了如何分析和验证循环内的最大时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述

思路:使用栈来模拟,但是,需要注意到如下几种情

  1. 可以创建两个栈,一个记录变量,一个记录时间复杂度。如果出现变量名重复,直接认为ERR,如果pop出来的时间复杂度为n,则将当前复杂度减一,最后只记录遍历过程中的最大复杂度。
  2. 如果某条语句进入不了循环,那么当前命令下的所有命令都失效。
  3. 如果某条语句出错,则剩下命令都不考虑。
    注意:如果一个字符串出现在行末,使用cin.next()时,要在加上一个cin.nextLine(),否则行末的回车符将影响下一次输入。但是,如果是连续的两个两行的cin.next(),则不需要加上cin.nextLine();

代码

	String getO(String s, String e) {
		if(!s.contentEquals("n") && e.contentEquals("n")) return "n";
		else if(s.contentEquals("n") && !e.contentEquals("n")) return "-1";
		else if(s.contentEquals("n") && e.contentEquals("n")) return "1";
		else {
			int si = Integer.parseInt(s);
			int ei = Integer.parseInt(e);
			if(si <= ei) return "1";
			else return "-1";
		}
	}
	boolean fit(String o, int n) {
		if(o.charAt(2) == '1') return n == 0;
		else return Integer.parseInt(o.substring(4, o.length()-1)) == n;
	}
	
//	boolean fit(String)
	void test() throws IOException {
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		for(int i = 0; i < n; i++) {
			Stack<String> vars = new Stack<>(); //存放变量名
			Stack<String> o_stack = new Stack<String>(); //存放复杂度
			int line = cin.nextInt();
			String y = cin.next();
			cin.nextLine();
			boolean err = false;
			boolean stop = false;
			String stop_char = "";
			int maxo = 0;
			
			int o = 0;
			for(int k = 0; k < line; k++) {
				String code = cin.nextLine();
				if(err) continue;
				
				if(code.charAt(0) == 'F') { 
					String[] cons = code.split(" ");
					if(vars.contains(cons[1])) { //如果变量冲突
						err = true;
					} else { 
						String reso = getO(cons[2], cons[3]);
						if(reso == "-1") { //如果此时无法进入循环,记录
							stop = true;
							stop_char = cons[1];
						}
						vars.push(cons[1]);
						o_stack.push(reso);
						if(reso == "n") o++;
						if(!stop) maxo = Math.max(maxo, o);
					}
				} else { // E
					//如果多了一个E
					if(vars.isEmpty()) err = true;
					else {
						String top = vars.pop();
						String top_o = o_stack.pop();
						if(top == stop_char) stop = false;
						if(top_o=="n") o--;
					}
				}
			}
			
			if(err || !vars.isEmpty()) {
				System.out.println("ERR");
			} else {
				if(fit(y, maxo)) System.out.println("Yes");
				else System.out.println("No");
			}
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值