洛谷 P1459 三值的排序 Sorting a Three-Valued Sequence\USACO 2.1.3

版权声明:喜欢请点个大拇指,感谢各位dalao。弱弱说下,转载要出处呦 https://blog.csdn.net/qq_35786326/article/details/84858003


题目:

传送门


分析:

知道普及-的题我居然一开始还不会 !!
大致思路是这样的,然后对它们做一次升序排序 ( s o r t ) (sort) ,随后再用一些玄学方法去求解,但很快,我们就会发现这样做并不能求到最优解(可能也可以,只是我太菜了)
所以我们就来思考下,到底是哪里出现了问题,然后就知道,直接做 s o r t sort 会出现一些很玄妙的 b u g bug 。所以我考虑换一种方法:我们在输入时统计每个数字出现的次数 ( s u m ) (sum)
这样我们就不需要做 s o r t sort ,而是用循环 i = 1 s u m [ 1 ] + s u m [ 2 ] i=1——sum[1]+sum[2] ,在循环中,我们判断当前位置上的数是否为 3 3 ,是,则答案直接 + 1 +1 ,因为我们遍历的位置不应该出现 3 3 ,故必定需要一次交换。而对于 1 2 1、2 ,我们只需再多判断下是否在范围内,否,也 + 1 +1
但判断 1 2 1、2 的时候不能对答案直接累加,应该用两个变量进行统计,最后取最大值,至于为什么,大家画个图,自己理解下,原理是交换一次,却可以是两个数回到目标位置


代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring> 
#include<cstdlib>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<map>
#include<list>
#include<ctime>
#include<iomanip>
#include<string>
#include<bitset>
#include<deque>
#include<set>
#define LL long long
#define ch cheap
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
int x[1001],sum[4],ans[4];
int main()
{
    int n=read();
    for(int i=1;i<=n;i++) x[i]=read(),sum[x[i]]++;
    for(int i=1;i<=sum[1]+sum[2];i++)
      if(x[i]==3) ans[3]++;
      else if(x[i]==2&&i<=sum[1]) ans[2]++;
      else if(x[i]==1&&i>sum[1]) ans[1]++;
    cout<<ans[3]+max(ans[1],ans[2]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35786326/article/details/84858003