指针做法,样例能过,评测全WA

P1678 烦恼的高考志愿

AC_love @ 2023-08-09 22:23:50

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, m, ans;
int st[114514];
int sc[114514];
signed main()
{
    cin >> m >> n;
    for(int i = 1; i <= m; i = i + 1)
        cin >> sc[i];
    sort(sc + 1, sc + 1 + m);
    for(int i = 1; i <= n; i = i + 1)
        cin >> st[i];
    sort(st + 1, st + 1 + n);
    int l = 1;
    for(int i = 1; i <= n; i = i + 1)
    {
        while(abs(sc[l] - st[i]) > abs(sc[l + 1] - st[i]) && l < n)
            l ++;
        ans += abs(sc[l] - st[l]);
    }
    cout << ans << endl;
    return 0;
}

by ybc2025chenyuyang @ 2023-08-09 22:24:25

@AC_love 是双指针吧


by Weizhuo_Zhao @ 2023-08-09 22:28:40

@AC_love 好臭的数组 双指针借鉴我的代码吧:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
int a[100005];
int n,m,p;
ll ans;
int search(int l,int r)
{
    int mid;
    while(l<r)
    {
        mid=l+(r-l)/2;
        if(a[mid]>p) r=mid;
        else l=mid+1;
    }
    return min(abs(a[l]-p),abs(a[l-1]-p));
}
int main()
{
    ios::sync_with_stdio(0);
    cin>>m>>n;
    for(int i=1;i<=m;i++) cin>>a[i];
    a[0]=a[1];
    sort(a+1,a+m+1);
    for(int i=1;i<=n;i++)
    {
        cin>>p;
        ans+=search(1,m);
    }
    cout<<ans;
    return 0;
}

by ncwzdlsd @ 2023-08-09 22:53:20

@AC_love %%%


by AC_love @ 2023-08-09 23:04:53

@Weizhuo_Zhao

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, m, ans;
int st[1919810];
int sc[1919810];
signed main()
{
    cin >> m >> n;
    for(int i = 1; i <= m; i = i + 1)
        cin >> sc[i];
    sort(sc + 1, sc + 1 + m);
    for(int i = 1; i <= n; i = i + 1)
        cin >> st[i];
    sort(st + 1, st + 1 + n);
    int l = 1;
    for(int i = 1; i <= n; i = i + 1)
    {
        while(st[i] - sc[l] > 0 && l < m)
            l ++;
        if(l != 1)
            ans += min(abs(sc[l] - st[i]), abs(sc[l - 1] - st[i]));
        else
            ans += abs(sc[l] - st[i]);
    }
    cout << ans << endl;
    return 0;
}

照着大佬的代码小改一下就过了,%%%


|