• SPOJ:Elegant Permuted Sum(贪心)


    Special Thanks: Jane Alam Jan
    *At moment in University of Texas at San Antonio - USA

    You will be given n integers A1A2A3...An. Find a permutation of these n integers so that summation of the absolute differences between adjacent elements is maximized.

    Suppose n = 4 and the given integers are 4 2 1 5. The permutation 2 5 1 4 yields the maximum summation. For this permutation sum = abs(2-5) + abs(5-1) + abs(1-4) = 3+4+3 = 10.

    Of all the 24 permutations, you won’t get any summation whose value exceeds 10. We will call this value, 10, the elegant permuted sum.

    Input

    The first line of input is an integer T (T < 100) that represents the number of test cases. Each case consists of a line that starts with n (1 < n < 51) followed by n non-negative integers separated by a single space. None of the elements of the given permutation will exceed 1000.

    Output

    For each case, output the case number followed by the elegant permuted summation.

    Example

    Input:
    3
    4 4 2 1 5
    4 1 1 1 1
    2 10 1 Output: Case 1: 10
    Case 2: 0
    Case 3: 9
    题意:给定组数,现在要你排序,使得排序后所有相邻两个数的差的和最大。
    思路:排序,选择第一个点为左起点pos1,最后一个点为右起点pos2,然后以左起点和右起点贪心选择最大路径。
    应用模型:X轴上有N个点,现在要你选择一个点作为起点,然后一个个的访问未访问过的点,问访问完所有点的最小距离是多少。
    #include<bits/stdc++.h>
    using namespace std;
    int main()
    {
        int T,N,i,Case=0,a[110],ans;;
        scanf("%d",&T);
        while(T--){
            scanf("%d",&N);
            for(i=1;i<=N;i++) scanf("%d",&a[i]);
            sort(a+1,a+N+1);
            ans=a[N]-a[1];
            int pos1=1,pos2=N,L=2,R=N-1;
            while(L<=R){
                int tmp=0,t[6];t[0]=-1; 
                t[1]=abs(a[pos1]-a[L]);
                t[2]=abs(a[pos2]-a[L]);
                t[3]=abs(a[pos1]-a[R]);
                t[4]=abs(a[pos2]-a[R]);
                for(i=1;i<=4;i++) if(t[i]>t[tmp]) tmp=i;
                ans+=t[tmp];
                if(tmp==1) pos1=L,L++;
                if(tmp==2) pos2=L,L++;
                if(tmp==3) pos1=R,R--;
                if(tmp==4) pos2=R,R--; 
            }
            printf("Case %d: %d
    ",++Case,ans);
        }
        return 0;
    }
  • 相关阅读:
    zblog如何更改数据库配置以及生效
    阿里云RDS数据库改造迁移方案
    如何突破微信的支付额度限制
    IIS进行URL重写——实现https重定向,文件类型隐藏访问重写,nodejs等服务重写等等
    windows设置本地域名解析
    自己写的加密网页,与百度网盘私密很相似,需要密码才能访问(原创)
    CSS3 translate、transform、transition区别
    IIS前端页面不显示详细错误解决方法
    CSS滚动条设置
    IIS支持PHP文件解析
  • 原文地址:https://www.cnblogs.com/hua-dong/p/8982117.html
Copyright © 2020-2023  润新知