题解P8708,stoll函数和to_string函数

· · 题解

看没人用 stoll 函数,所以我来写一下。

题意

给出一个长度为的数组A 1,A 2,⋯,A n。可以从中两个数 和 ,然后拼接起来。

什么是 stoll 函数

stoll 的功能是将字符串转化为 long long类型的整数。

示例。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long stoll(constwstring&str,size_t*idx=0,int base=10);
}

其中:str 字符串对象。

idx 指向size_t类型对象的指针,其值由函数设置为数值后str中下一个字符的位置。 此参数也可以是空指针,在这种情况下不使用它。

base 确定有效字符及其解释的数字基数(找了两个博客都是这样解释的,不过应该就是进制)。

什么是 to_string 函数

to_string 函数的作用是将数字常量转换为字符串,返回值为转换完毕的字符串。

示例。

#include<string>
using namespace std;
int main()
{
    string s=to_string(1+2+4+5);
}

使用 to_string 函数和 to_string 函数需要使用#include<string>头文件。

思路

这道题的思路就是先将数组排序,然后用to_string将数字变成字符串,接着两个字符串相加,再用stoll函数变回数字。如果拼接后的数字小于 k,那么因为 r 指针指向的是目前的最大值,所以 [l,r] 区间内的所有数字与 l 拼接的结果都小于 k,所以答案加上 r-l,并且更新左指针 l++。 如果拼接后的数字等于 k,答案也要加上 r-l,但是此时需要同时更新,l++,r--。

最后附上代码~~

#include<bits/stdc++.h>
using namespace std;
int a[10000005]; 
int main()
{
    int n,k,ans=0;
    cin>>n>>k;
    int l=1,r=n;
    for(int i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+1+n);
    while(l<=r)
    {
        if(stoll(to_string(a[l])+to_string(a[r]))<=k)
        {
            ans+=r-l;
            l++;
        }
        else r--;
    }
    l=1,r=n;
    while(l<=r)
    {
        if(stoll(to_string(a[r])+to_string(a[l]))<=k)
        {
            ans+=r-l;
            l++;
        }
        else r--;
    }
    cout<<ans;
    return 0;
}