1 条题解

  • 0
    @ 2024-8-23 13:49:26

    这个题很多人一看就以为是一道模拟,实则不然。如果你用模拟的话,那么就会 因为这个数据范围实在是太可爱友好了: 但是题目还是给我们留了一条活路的,那就是: 所以我们就可以在每次插入的时候直接对其进行排序,那么如果我们需要排序的话,我们就需要一个结构体来存储它之前的编号。然后再需要查找的时候,直接进行输出就可以了。 提前解释一下代码中用两个for循环就可以排序的方法: 这种方法的思路是首先从大到小遍历整个数组。如果有比这个数大的就将两个数交换。然后接下来再用第二个for循环从前往后从小到大遍历整个数组。这样两个for循环下来,我们就可以保证这一个数据是在正确的位置上了。 最后我们来计算一下时间复杂度,为什么按照这样的思路来写不会超时呢?因为每次插入的时间复杂度是O(n)O(n),而每次查找所需要的时间复杂度是O(1)O(1),所以就能保证他会

    AC code

    #include <bits/stdc++.h>
    #define ios ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
    using namespace std;
    int t[8010];
    struct node{
    	int zhi;
    	int hao;	
    }a[8010];
    bool cmp(node x,node y){
    	if(x.zhi!=y.zhi) return x.zhi<y.zhi;
    	return x.hao<y.hao;
    }
    int main(){
    	ios;
    	int n,q;
    	cin>>n>>q;
    	for(int i=1;i<=n;i++){
    		cin>>a[i].zhi;
    		a[i].hao=i;
    	}
    	sort(a+1,a+n+1,cmp);
    	for(int i=1;i<=n;i++){
    		t[a[i].hao]=i;
    	}
    	for(int i=1;i<=q;i++){
    		int opt,x,v;
    		cin>>opt;
    		if(opt==1){
    			cin>>x>>v;
    			a[t[x]].zhi=v;
    			for(int j=n;j>=2;j--)
    				if(cmp(a[j],a[j-1])){
    					node k=a[j];
    					a[j]=a[j-1];
    					a[j-1]=k;
    				}
    			for(int j=2;j<=n;j++)
    				if(cmp(a[j],a[j-1])){
    					node k=a[j];
    					a[j]=a[j-1];
    					a[j-1]=k;
    				}
    			for(int i=1;i<=n;i++)
    				t[a[i].hao]=i;
    		}else{
    			cin>>x;
    			cout<<t[x]<<endl;
    		}
    	}
    	return 0;
    }
    

    信息

    ID
    638
    时间
    1000ms
    内存
    512MiB
    难度
    7
    标签
    递交数
    62
    已通过
    13
    上传者