题解:[NOIP 2017 提高组] 时间复杂度

题目传送门

模拟

对于这种模拟题,其实题解也几乎没什么好说的——依据题意模拟即可。

注意事项

  • 某些循环体不会被执行,其内部的循环体也不会被执行,不应当计入时间复杂度。
  • 注意变量的上下界 \(x,y\)\(x>y\) 时不会执行,\(x=y\) 时为常数复杂度(包括 \(x=y=n\))。

AC 代码

//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
#include<unordered_set>
using namespace std;
constexpr const int L=100;
int l;
string oType;//"1","value"
int oValue;
void getO(){
	string pl;
	cin>>pl;
	pl=pl.substr(2,pl.size()-3);
	if(pl=="1"){
		oType="1";
	}else{
		oType="value";
		oValue=atoi(pl.substr(2,pl.size()-2).c_str());
	}
}
struct solve{
	char type;
	string value,valueType;
	bool can;//能否被执行 
}a[L+1];
void getSolve(){
	for(int i=1;i<=l;i++){
		string pl;
		cin>>pl;
		a[i].type=pl[0];
		a[i].can=true;
		if(a[i].type=='F'){
			cin>>a[i].value;
			string x,y;
			cin>>x>>y;
			if(x=="n"&&y=="n"||x!="n"&&y!="n"){
				a[i].valueType="1";
				if(x!="n"){
					if(atoi(x.c_str())>atoi(y.c_str())){
						a[i].can=false;
					}
				} 
			}else{
				a[i].valueType="n";
				if(x=="n"&&y!="n"){
					a[i].can=false;
				}
			}
		}
	}
}
string query(){
	int Max=0;
	//变量id,n的层数 
	vector<pair<int,int>>s;
	unordered_set<string>flag;
	//cnt>0:不执行 
	int cnt=0;
	for(int i=1;i<=l;i++){
		if(a[i].type=='F'){
			//变量冲突 
			if(flag.count(a[i].value)){
				return "ERR";
			}
			cnt+=!a[i].can;
			int w=(a[i].valueType=="n"&&!cnt);
			if(s.size()){
				w+=s.back().second;
			}
			Max=max(Max,w);
			s.push_back({i,w});
			flag.insert(a[i].value);
		}else{
			if(s.size()){
				flag.erase(a[s.back().first].value);
				cnt-=!a[s.back().first].can;
				s.pop_back();
			}else{
				//F,E不匹配:缺 F 
				return "ERR";
			}
		}
	}
	//F,E不匹配:缺 E 
	if(s.size()){
		return "ERR";
	}
	bool mode;
	if(oType=="1"){
		mode=!Max;
	}else{
		mode=(Max==oValue);
	}
	return (mode?"Yes":"No");
}
int main(){
	/*freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);*/
	
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	int T;
	cin>>T;
	while(T--){
		cin>>l; 
		getO();
		getSolve();
		cout<<query()<<endl;
	}
	
	/*fclose(stdin);
	fclose(stdout);*/
	return 0;
}
posted @ 2025-07-21 21:43  TH911  阅读(10)  评论(0)    收藏  举报