uva12299(RMQ with Shifts)

思路:这题一眼就是线段树单点更新,,,训练开着题的时候就是傻逼了,,,一看数据很大,时间很小,TLE定了,,,3个小时后再来看,发现别人过的时间都只有300-ms,,,然后再读题的时候就看见了 <= 30,,,然后update的时间就很小了,,所以就可以线段树过题。。。。还是自己太弱了

// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
// #define DEBUG
#ifdef DEBUG
#define debug(...) printf( __VA_ARGS__ )
#else
#define debug(...)
#endif
#define MEM(x,y) memset(x, y,sizeof x)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int maxn = 1e5 + 10;
struct Seg{
	int val,l,r;
	Seg(int l=0,int r=0,int val=0){
		this->l=l;
		this->r=0;
		this->val=val;
	}
}Seg[maxn<<2];
int n,m,arr[maxn];
void up(int rt){
	Seg[rt].val = min(Seg[rt<<1].val,Seg[rt<<1|1].val);
}
void build(int rt,int L,int R){
	Seg[rt].l = L,Seg[rt].r = R;
	if (L == R){
		Seg[rt].val = arr[L];
		return;
	}
	int mid = (L + R)/2;
	build(rt<<1,L,mid);
	build(rt<<1|1,mid+1,R);
	up(rt);
}
void updata(int rt,int pos,int val){
	if (Seg[rt].l == pos && Seg[rt].r == pos){
		Seg[rt].val = val;
		return;
	}
	int mid = (Seg[rt].l + Seg[rt].r)/2;
	if (pos <= mid) updata(rt<<1,pos,val);
	else updata(rt<<1|1,pos,val);
	up(rt);
}
int query(int rt,int L,int R){
	if (L <= Seg[rt].l && Seg[rt].r <= R) return Seg[rt].val;
	int mid = (Seg[rt].l + Seg[rt].r)/2;
	if (R <= mid) return query(rt<<1,L,R);
	else if (L > mid) return query(rt<<1|1,L,R);
	else return min(query(rt<<1,L,R),query(rt<<1|1,L,R));
}
void get(int& n,int *num,char *s){
	n = 0;
	int len = strlen(s);
	int u = 0;
	for (int i = 0;i < len;i++){
		if (s[i] >= '0' && s[i] <= '9')
			u = u * 10 + s[i] - '0';
		else if (s[i] == ',' || s[i] == ')'){
			num[n++] = u;
			u=0;
		}else u = 0;
	}
}
void solve(){
	// debug("time\n");
	int n,num[50];
	char order[50];
	scanf("%s",order);
	// gets(order);
	// cout << order << endl;
	// debug("%s\n",order);
	get(n,num,order);
	if (order[0] == 's'){
		// debug("n = %d\n",n);
		int tmp = arr[num[0]];
		for (int i = 0;i < n - 1;i++){
			updata(1,num[i],arr[num[i+1]]);
			arr[num[i]] = arr[num[i+1]];
		}
		updata(1,num[n-1],tmp);
		arr[num[n-1]] = tmp;
	}else if (order[0] == 'q'){
		printf("%d\n",query(1,num[0],num[1]));
	}
}
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	int cnt = 0;
	while(scanf("%d%d",&n,&m) == 2){
		// debug("cnt = %d,n = %d,m = %d\n",++cnt,n,m);
		for (int i = 1;i <= n;i++)
			scanf("%d",&arr[i]);
		build(1,1,n);
		getchar();
		for (int i = 0;i < m;i++){
			solve();
		}
	}
	return 0;
}


你可能感兴趣的:(数据结构-线段树,数据结构-树)