2025_12_15

洛谷——P1544 , 数组题目 , 知识点 : 数位统计公式 ,

点击查看代码
//base = 1 , 10 , 100 , 1000 ...
//base = 1 → 个位 ; base = 10 → 十位 ; base = 100 → 百位 ;....
//high = n / (base * 10) ;
//cur = (n / base)% 10 ;
//low = n % base ;
//
//if(cur > d)
//res += (high + 1) * base ;
//else if(cur == d)
//res += high * base + low + 1 ;
//else if(cur < d)
//res += high * base ;

#include <iostream>
using namespace std;

long long count(long long n, int d) {
    if (n < 0) return 0;
    long long res = 0;
    for (long long base = 1; base <= n; base *= 10) {
        long long high = n / (base * 10);
        long long cur  = (n / base) % 10;
        long long low  = n % base;

        if (d != 0) {
            if (cur > d) res += (high + 1) * base;
            else if (cur == d) res += high * base + low + 1;
            else res += high * base;
        } else {
            if (high == 0) continue;
            if (cur > 0) res += (high - 1) * base + base;
            else res += (high - 1) * base + low + 1;
        }
    }
    return res;
}

int main() {
    long long M, N;
    cin >> M >> N;

    for (int d = 0; d <= 9; d++)
        cout << count(N, d) - count(M - 1, d) << " ";
}

sort() 函数
STL中的sort()函数并非只是普通的快速排序,除了对普通的快速排序进行了优化,它还结合了插入排序和堆排序。根据不同的数量级别以及不同情况,能自动选择合适的排序方法。
在cpp中使用sort()函数需要引用#include 头文件,
sort()函数可以对指定区间的所有元素进行排序。它有三个参数sort(begin,end,cmp),其中begin为指向sort()的数组的第一个元素的指针,end为指向sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则(可以不写,不写默认为从小到大排序),想要从大到小,可以写成greater(),或者float,double。
如 : int num[10] = {6,5,8,7,9,2,1,3,4,0} ;
sort(num , num+10 ,greater());//输出结果为9,8,7,6,5,4,3,2,1,0;
自定义排序准则
sort()函数可以自定义排序准则,以便满足不同的排序顺序。
如我们按照每个数的个位进行由大到小进行排序,
如 :

include

include

using namespace std;

bool cmp(int x,int y){
return x % 10 > y % 10;
}

int main(){
int num[10] = {65,59,96,13,21,80,72,33,44,99};
sort(num,num+10,cmp);
for(int i=0;i<10;i++){
cout<<num[i]<<" ";
}//输出结果:59 99 96 65 44 13 33 72 21 80

return 0;

}

posted on 2025-12-15 21:28  _hkn  阅读(2)  评论(0)    收藏  举报