8.17 总结
3Luby3
·
2025-08-17 22:22:06
·
个人记录
T1 T637969 转变
思路
嗯~从 k+1 开始输出到 n ,然后补 k 个 0 ,就这么简单。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxx=500;
int n,k,a[maxx];
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>k;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=k+1;i<=n+k;i++){
if(i<=n) cout<<a[i]<<" ";
else cout<<0<<" ";
}
return 0;
}
T2 T638034 真实社交
思路
最开始我是写的 map,后来一看。。。嗯~~~ n\leq10^9 !!!,这怎么行。于是我就用一个二维 bool 数组操作了一下。。。
那如何写正解就需要用 pair 数对,然后存放在 map 的第一个位置。用这个数对表示 a 与 b 的粉丝关系,a 关注了 b 就标记为 1 。
代码
#include<bits/stdc++.h>
//#define int long long
using namespace std;
int n,q;
map<pair<int,int> ,bool> mp;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>q;
while(q--){
int op,a,b;
cin>>op>>a>>b;
if(op==1){
mp[{a,b}]=1;
}
else if(op==2){
if(mp.count({a,b})){
mp.erase({a,b});
}
}else{
if(mp.count({a,b}) && mp.count({b,a})){
cout<<"Yes\n";
}else cout<<"No\n";
}
}
return 0;
}
T3 T638156 落落的去维护数组
思路
直接根据代码来说。
这样来写的话(运用偏移量)可以显著降低全部更改的时间复杂度,从 $O(n)$ 瞬间变成 $O(1)$。
来仔细讲一下两个 $op$:
- $op=2$:
先判断时间的先后关系,如果**从没有被修改** 或 **上次修改在全局赋值之前**,则重置为 $0$ 再加 $k$,否则的话直接加上 $k$ 就行了。
- $op=3$:
- 如果该元素修改时间早于全局赋值时间,则直接输出全局值
- 如果修改时间晚于全局赋值时间,则输出局部值+全局值
- 如果修改时间等于全局赋值时间,则直接输出局部值
## 代码
```cpp line-numbers
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxx=2e5+10;
int n,q,a[maxx],t[maxx];
int lastval,lasttime;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
cin>>q;
for(int i=1;i<=q;i++){
int op,x,k;
cin>>op;
if(op==1){
cin>>k;
lasttime=i;
lastval=k;
}
else if(op==2){
cin>>x>>k;
if(lasttime==0) a[x]+=k;
else if(t[x]>lasttime) a[x]+=k;
else a[x]=0,a[x]+=k;
t[x]=i;
}
else{
cin>>x;
if(t[x]<lasttime){
cout<<lastval<<endl;
}
else if(t[x]>lasttime){
cout<<a[x]+lastval<<endl;
}
else cout<<a[x]<<endl;
}
}
return 0;
}
```
# [T4 T638430 交叉区间](https://www.luogu.com.cn/problem/T638430?contestId=269857)
## 思路
这道题既然我们清楚正着求 $(i,j)$ 难,那我们不如先求出所有没有相交的再用总数去减。总数是 $C^n_2=\frac{n\times{n-1}}{2}$。
不相交一共有两种情况:
- 区间 $i$ 完全在区间 $j$ 的左侧
- 区间 $i$ 完全在区间 $j$ 的右侧
利用好左右等条件,我们就可以用二分的两个函数 `upper_bound()` 和 `lower_bound()`。
使用 `upper_bound()` 在 $b$ 数组中查找第一个**大于** $R$ 的**左端点**,计算有多少区间完全在当前区间右侧
使用 `lower_bound() `在 $c$ 数组中查找第一个**不小于** $L$ 的**右端点**,计算有多少区间完全在当前区间左侧
## 代码
```c++ line-numbers
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxx=5e5+10;
int n,b[maxx],c[maxx];
struct node{
int l,r;
}a[maxx];
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].l>>a[i].r;
b[i]=a[i].l;
c[i]=a[i].r;
}
sort(b+1,b+1+n);
sort(c+1,c+1+n);
int ans=0;
for(int i=1;i<=n;i++){
int L=a[i].l,R=a[i].r;
int x=upper_bound(b+1,b+1+n,R)-b;
int num1=n-x+1;
x=lower_bound(c+1,c+1+n,L)-c;
int num2=x-1;
ans+=num1+num2;
}
ans/=2;
cout<<n*(n-1)/2-ans;
return 0;
}
```