72 TLE 求优化
查看原帖
72 TLE 求优化
1126325
Indestructible楼主2024/10/13 12:51
// Attention: This code is NOT from AI.
// Now statement: Time Limit Exteeded. (O(N^2))
#include<bits/stdc++.h>
#define int long long
#define N 2012428
using namespace std;
char s[N];
int n,m,x,cnt_s,cnt_ex=1;
int cnt_ask[N],cnt,res; // Use stack (count the "?") to make Expr.
struct Expr{        // It looks like a binary tree.
	bool is_bigger; // ">" is 1 and "<" is 0.
	int num;        // The number after ">" or "<".
	int first;      // The expr id after "?" (0 means none).
	int second;     // The expr id after ":" (0 means none).
}ex[N];
inline void rd(int &res){ // Read a integer number.
	char c;res=0;bool flag=0;
	while (c=getchar(),c<48||c>57) flag=c=='-';
	do res=(res<<3)+(res<<1)+(c^48);
	while (c=getchar(),c>=48); res=flag?-res:res;
}
int calc(int x){
	int now=1;
	while (ex[now].first&&ex[now].second)
		if (ex[now].is_bigger) now=x>ex[now].num?ex[now].first:ex[now].second;
		else now=x<ex[now].num?ex[now].first:ex[now].second;
	return ex[now].num;
}
signed main(){
	rd(n),rd(m); // Input faster.
	char c; while (c=getchar(),c==' '||c=='\r'||c=='\n');
	do s[++cnt_s]=c; while (c=getchar(),c!=' '&&c!='\r'&&c!='\n');
	// Make the input string to some Expr.
	cnt_ask[++cnt]=1;
	for (int i=1;i<=cnt_s;i++){
		if (isdigit(s[i])) res=res*10+s[i]-'0';
		if (s[i]=='?') ex[cnt_ask[cnt]].first=++cnt_ex,
		/* Push in. */ ex[cnt_ask[cnt]].num=res,
					   cnt_ask[++cnt]=cnt_ex,res=0;
		if (s[i]==':') ex[cnt_ask[cnt]].num=res,
		/* Pop out. */ ex[cnt_ask[--cnt]].second=++cnt_ex,
					   cnt_ask[cnt]=cnt_ex,res=0;
		if (s[i]=='>') ex[cnt_ask[cnt]].is_bigger=1;
		if (i==cnt_s) ex[cnt_ask[cnt]].num=res;
	}
	for (int i=1;i<=m;i++) rd(x),printf("%lld\n",calc(x));
	return 0;
}
2024/10/13 12:51
加载中...