• ZOJ3798 Abs Problem


    题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3798

    学会了对于序列用next_permutation暴力打表

    可以先打表找规律

    #include<cstdio>
    #include<algorithm>
    #define INF 0x3f3f3f3f//
    #define N 100
    using namespace std;
    int seq[N];//保存当前序列
    int mi[N], ma[N];//保存最小值最大值相应序列
    int calc(int n)//总排序数
    {
        int p = 1;
        for (int i = 1; i <= n; ++i)
            p *= i;
        return p;
    }
    int main()
    {
        int n;
        while (~scanf("%d", &n))
        {
            for (int i = 1; i <= n; ++i)
                seq[i] = i;
            int k = calc(n), MIN = INF, MAX = -INF;
            for (int i = 0; i < k; ++i)
            {
                int b;
                next_permutation(seq + 1, seq + n + 1);
                for (int i = 1; i <= n; ++i)
                {
                    if (i == 1) b = seq[i];
                    else b = abs(b - seq[i]);
                }
                if (b <= MIN)
                {
                    MIN = b;
                    for (int i = 1; i <= n; ++i)
                        mi[i] = seq[i];
                }
                if (b>=MAX)
                {
                    MAX = b;
                    for (int i = 1; i <= n; ++i)
                        ma[i] = seq[i];
                }
            }
            printf("%d %d
    ", MIN, MAX);
            for (int j = 1; j <= n; ++j)
                printf("%d ", mi[j]);
            puts("");
             for (int j = 1; j <= n; ++j)
                 printf("%d ", ma[j]);
             puts("");
         }
         return 0;
    }

    规律:逆序时最小,将逆序最大放到末位时最大

    n%4==3或0时,最小值为0,其余都为1

    举个例子:序列7 6 5 4 3 2 1

    此时该序列为最小值,会发现:从7开始每4个数的绝对值为0,每两个数为1,所以若n%4==3时,剩下的最后3个为3 2 1,易得最小值为0,n%4==0、1、2时同理。

    最大值MAX(n)=n-MIN(n-1)

    AC代码:

    #include<cstdio>
    int getMin(int n)
    {
        if (n % 4 == 3 || n % 4 == 0)
            return 0;
        return 1;
    }
    int main()
    {
        int n;
        while (~scanf("%d", &n))
        {
            printf("%d %d
    ", getMin(n), n - getMin(n - 1));
           for (int i = n; i > 0; --i)
           {
                if (i > 1)printf("%d ", i);
                else printf("%d
    ", i);
           }
           for (int i = n-1; i > 0; --i)
               printf("%d ", i);
           printf("%d
    ", n);
        }
        return 0;
    }
  • 相关阅读:
    python读取配置文件
    日志截取
    QJsonObject
    OpenStack
    生成器迭代器正则视频笔记
    使用Qt.createComponent 动态加载组件
    linux 远程执行命令
    Django 建立工程连接数据库
    arm基础1
    QSetting的用法
  • 原文地址:https://www.cnblogs.com/-Unc/p/4162530.html
Copyright © 2020-2023  润新知