8.2课堂总结

最后更新于 2025-08-03 09:24:23
分类 个人记录

课堂总结:

P1639 [USACO18FEB] Teleportation B

代码思路:

只有两种可能:
1.用传送门
2.不用传送门
取min就可以了

正确代码:

#include<bits/stdc++.h>
using namespace std;
int main(){
    int x, y, a, b;
    cin >> a >> b >> x >> y;
    if(x > y)swap(x,y);
    if(a > b)swap(a,b);
    cout << min(abs(a-x)+abs(b-y),b-a);
    return 0;
}

B4239 [海淀区小学组 2025] 拜访朋友

代码思路:

1.(x0 < x[1])x[n-1]-x0;
2.(x0 > x[n])x0-x[2];
3.
    往左
        1.x0-x[1]+x[n-1]-x[1]
        2.x0-x[2]+x[n]-x[2]
    往右
        1.x[n-1]-x0+x[n-1]-x[1]
        2.x[n]-x0+x[n]-x[2]

正确代码:

#include<bits/stdc++.h>
using namespace std;
int a[100005];
int main(){
    int n, x;
    cin >> n >> x;
    for(int i = 1;i <= n;i++)cin >> a[i];
    sort(a+1,a+1+n);
    if(n == 1)cout << 0;
    else if(x <= a[1])cout << a[n-1] - x;
    else if(x >= a[n])cout << x - a[2];
    else cout << min(min(a[n]-x+a[n]-a[2],a[n-1]-x+a[n-1]-a[1]),min(x-a[1]+a[n-1]-a[1],x-a[2]+a[n]-a[2]));
    return 0;
}

P1842 [USACO05NOV] 奶牛玩杂技

代码思路:

正确代码:

#include<bits/stdc++.h>
using namespace std;
struct node{
    long long w, s;
}a[50005];
bool x(node a, node b){
    return a.w+a.s<b.w+b.s;
}
int main(){
    long long n, ans = LONG_LONG_MIN, sum = 0;
    cin >> n;
    for(int i = 1;i <= n;i++)cin >> a[i].w >> a[i].s;
    sort(a+1,a+1+n,x);
    for(int i = 1;i <= n;i++){
        ans = max(ans,sum-a[i].s);
        sum += a[i].w;
    }
    cout << ans;
    return 0;
}