T638034 真实社交
错误代码:
直接拿的暴力分,没有离散化数据
#include<bits/stdc++.h>
using namespace std;
bool vis[1005][1005];
int n,q;
int main(){
cin >> n >> q;
while(q--){
int op,a,b;
cin >> op >> a >> b;
if(op == 1){
vis[a][b] = 1;
}
else if(op == 2) vis[a][b] = 0;
else{
if(vis[a][b] == 1 and vis[b][a]) cout << "Yes" << '\n';
else cout << "No" << '\n';
}
}
return 0;
}分析:数据过大
#include<bits/stdc++.h>
using namespace std;
map <pair<int,int> , bool> mp;//使用二维map存储
int n,q;
int main(){
cin >> n >> q;
while(q--){
int op,a,b;
cin >> op >> a >> b;
if(op == 1){
mp[{a,b}] = 1;
}
else if(op == 2) mp[{a,b}] = 0;
else{
if(mp[{a,b}] == 1 and mp[{b,a}]) cout << "Yes" << '\n';
else cout << "No" << '\n';
}
}
return 0;
}
T638156 落落的去维护数组
错误代码:暴力拿了74分
#include<bits/stdc++.h>
using namespace std;
bool vis[1005][1005];
long long a[200005];
int n,q;
int main(){
cin >> n;
for(int i = 1;i <= n;i++) cin >> a[i];
cin >> q;
while(q--){
long long op,k,ii;
cin >> op ;
if(op == 1){
cin >> k;
for(int i = 1;i <= n;i++) a[i] = k;//超时
}
else if(op == 2){
cin >> ii >> k;
a[ii] += k;
}
else{
cin >> ii;
cout << a[ii] << '\n';
}
}
return 0;
}分析:记录操作1的最后执行时间为last_time,记录操作1最后执行的k,如果last_time == 0输出a[x]
当t[i] < last_time时输出last_k
当t[i] > last_tim输出a[x] + last_k
#include<bits/stdc++.h>
using namespace std;
bool vis[1005][1005];
long long a[200005],t[200005];//t[n]记录每一个元素最后更新的时间
int n,q;
int main(){
cin >> n;
for(int i = 1;i <= n;i++) cin >> a[i];
cin >> q;
long long last_time = 0,last_k = 0;//last_time记录操作1的最后执行时间,last_k记录操作1最后执行的k
for(int i = 1;i <= q;i++){
long long op,k,x;
cin >> op;
if(op == 1){
cin >> k;
last_time = i;
last_k = k;
}
else if(op == 2){
cin >> x >> k;
if(last_time == 0) a[x] += k;
else if(t[x] < last_time) a[x] = k;
else if(t[x] > last_time) a[x] += k;
t[x] = i;//更新最后更新时间
}
else{
cin >> x;
if(last_time == 0) cout << a[x] << '\n';
else if(t[x] < last_time) cout << last_k << '\n';
else if(t[x] > last_time) cout << a[x] + last_k << '\n';
}
}
return 0;
}
T638430 交叉区间
分析:两个区间不相交只有以下两种情况:
l_i > r_i r_j < l_i
(l_i,l_j、r_i,r_j为两个区间的左右端点)
所有只要用两个数组(b,c)分别存储左右端点,把b数组排序,二分查找第一个>r_i的位置pos1,令sum+=n-pos+1,将c数组排序,二分查找第一个>=l_i的位置pos,sum+=pos-1
#include<bits/stdc++.h>
using namespace std;
bool vis[1005][1005];
long long b[500005],c[500005];
long long n,q;
struct node{
long long l,r;
};
node a[500005];
int main(){
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 + n + 1);
sort(c + 1,c + n + 1);
long long sum = 0;
for(int i = 1;i <= n;i++){
long long pos1 = upper_bound(b + 1,b + 1 + n,a[i].r) - b;
sum += n - pos1 + 1;
long long pos2 = lower_bound(c + 1,c + 1 + n,a[i].l) - c;
sum += pos2 - 1;
}
sum/=2;
cout << n * (n - 1) / 2 - sum;//相交对数 = 总区间对数 - 不相交对数
return 0;
}