51nod 1096 + 51nod 1108 + 51nod 1110 中位数专题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37428263/article/details/89139796

51 nod 1096

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
    int n;
    scanf("%d",&n);
    int a[10005];
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    sort(a+1,a+n+1);
    if(n&1) {
        LL sum=0;
        for(int i=1;i<=n;i++)
        {
            sum+=1l*abs(1l*a[n/2+1]-a[i]);
        }
        printf("%lld\n",sum);
    }
    else {
        LL sum=0;
        for(int i=1;i<=n;i++)
        {
            sum+=1l*abs(1l*a[n/2]-a[i]);
        }
        printf("%lld\n",sum);
    }
    return 0;
}

51nod 1108

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=1e4+5;
struct point{
    int x,y,z;
};
int main()
{
    int n;
    scanf("%d",&n);
    int x1[maxn],y1[maxn],z1[maxn];
    point p[maxn];
    for(int i=1;i<=n;i++)
    {
        scanf("%d%d%d",&x1[i],&y1[i],&z1[i]);
        p[i].x=x1[i],p[i].y=y1[i],p[i].z=z1[i];
    }
    sort(x1+1,x1+1+n);
    sort(y1+1,y1+1+n);
    sort(z1+1,z1+1+n);
    LL sum=0;
    point pos;
    if(n&1) {
            pos.x=x1[n/2+1];
            pos.y=y1[n/2+1];
            pos.z=z1[n/2+1];
    }
    else {
            pos.x=x1[n/2];
            pos.y=y1[n/2];
            pos.z=z1[n/2];
    }
    for(int i=1;i<=n;i++)
    {
        sum+=1l*( 1l*abs(1l*pos.x-p[ i ].x ) +1l*abs(1l* pos.y - p[ i ].y )+1l*abs(1l* pos.z - p[ i ].z ));
    }
    printf("%lld\n",sum);
    return 0;
}

51nod 1110

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=1e4+5;
struct S{
    LL p,dist;
};
bool cmp(S s1,S s2)
{
    return s1.p<s2.p;
}
int main()
{
    int n;
    scanf("%d",&n);
    S pk[maxn];
    LL cnt=0;
    for(int i=1;i<=n;i++)
    {
        int pos,weight;
        scanf("%d%d",&pos,&weight);
        cnt+=weight;
        pk[i].p=pos;
        pk[i].dist=weight;
    }
    LL pos;
    sort(pk+1,pk+n+1,cmp);
    if(cnt&1) {
        LL k=cnt/2+1,last=1,s;
        for(int i=1;i<=n;i++)
        {
            s=last+pk[i].dist-1;
            if(k>=last&&k<=s) {
                pos=pk[i].p;
                break;
            }
            else {
                last=s+1;
            }
        }
    }
    else {
        LL k=cnt/2,last=1,s;
        for(int i=1;i<=n;i++)
        {
            s=last+pk[i].dist-1;
            if(k>=last&&k<=s) {
                pos=pk[i].p;
                break;
            }
            else {
                last=s+1;
            }
        }
    }
    LL sum=0;
    for(int i=1;i<=n;i++)
    {
            sum+=1l*abs(1l*pos-pk[i].p)*1l*pk[i].dist;
    }
    printf("%lld\n",sum);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37428263/article/details/89139796
今日推荐