跳到正文

个人记录

401 Day4

the_Wolf_King约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月28日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 3 分钟

版本

  1. v1当前

落落的去维护数组

这题我就是直接用模拟的了74分,模拟代码也就那样就不放出来了,这题正解是通过存储修改值k的值和时间然后再判断每个数的修改时间然后就可以把修改为k的那一段省掉成O(n)O(n)的了。

代码

C++
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
#define int long long
int a[N];
int t[N];
signed main(){
	int n,q;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	cin>>q;
	int last_k=0;
	int last_time=0;
	int i=1;
	while(q--){
		int op;
		cin>>op;
		if(op==1){
			int k;
			cin>>k;
			last_k=k;//把最新的修改值存下来
			last_time=i;//存下修改的时间
		}
		else if(op==2){
			int x,k;
			cin>>x>>k;
			if(last_time==0)a[x]+=k;
			else if(t[x]<last_time)a[x]=k;//如果他这个数的修改时间比k的修改时间小就把它变成k。
			else if(t[x]>last_time)a[x]+=k;
			t[x]=i;
		}
		else if(op==3){
			int x;
			cin>>x;
			if(last_time==0)cout<<a[x]<<endl;
			else if(t[x]<last_time)cout<<last_k<<endl;
			else if(t[x]>last_time)cout<<a[x]+last_k<<endl;
		}
		i++;

	}
	return 0;
}

T2交叉区间

这题要用到二分查找,但我有一个方法首先一样的先对区间的起始点排序,用一个优先队列来记录可能与其他区间相交的区间的右端点,遍历一遍这个区间,然后我们就找不可能和后面的其他相交的,把不可能与后面的其他区间相交的出队,然后记录一下当前q的长度就是这一段的相交区间的数量,然后再把新的这个ai.ra_{i.r}入队,然后这个每次加的ans就是答案了。

之前做一个类似题的加强版就用了这种写法,然后忘记怎么写了,还有小根堆的那个定义实在是太长了,导致比赛时没写出来。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;

struct nd {
    int l, r;
}a[N];

bool cmp(nd x, nd y) {
    return x.l < y.l;
}

priority_queue<int, vector<int>, greater<int>> q;

int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) 
        cin >> a[i].l >> a[i].r;
    
    sort(a + 1, a + n + 1, cmp);
    long long ans = 0;
    
    for (int i = 1; i <= n; i++) {
        while (!q.empty() && q.top() < a[i].l) 
            q.pop();
        ans += q.size();
        q.push(a[i].r);
    }
    cout << ans;
    return 0;
}
原文