avatar
fireworks99
keep hungry keep foolish

sprintf

头文件

#include

作用之一

数字转字符串

HDU 6468

http://acm.hdu.edu.cn/showproblem.php?pid=6468

Code of TLE

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e6 + 5;

struct node
{
    char s[10];
} a[N];

bool cmp(node a, node b)
{
    return strcmp(a.s, b.s) < 0;
}

void slove(int n, int k)
{
    for(int i = 1; i <= n; ++i)
        sprintf(a[i].s, "%d", i);
    sort(a + 1, a + n + 1, cmp);
    cout << a[k].s << '\n';
}

int main()
{
    int t, n, k;
    cin >> t;
    while(t--)
    {
        scanf("%d%d", &n, &k);
        slove(n, k);
    }
    return 0;
}

虽然这份代码超时了,但sprintf的这个作用还是很强的,不知道他之前还模拟这个过程

Code of privious TLE

#include <set>
#include <queue>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

string s[1000005];

bool cmp(string a, string b)
{
    return a < b;
}


int main()
{
    int t;
    cin >> t;
    int n, k;
    while(t--)
    {
        scanf("%d%d", &n, &k);
        for(int i = 1; i <= n; ++i)
        {
            int tem = i;
            while(tem)
            {
                s[i] = s[i] + char(tem % 10 + '0');
                tem /= 10;
            }
            reverse(s[i].begin(), s[i].end());
        }
        sort(s + 1, s + n + 1, cmp);
        cout << s[k] << '\n';
    }
    return 0;
}

还有stringstream的按空格截取

#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;

int main()
{
    int t;
    cin >> t;
    getchar();
    while(t--)
    {
        string s, tem;
        getline(cin, s);
        bool flag = 0;

        ///按空格截取s为tem
        stringstream ss(s);
        while(ss >> tem)
        {
            if(flag)
                cout << ' ';
            flag = 1;
            reverse(tem.begin(), tem.end());
            cout << tem ;
        }
        cout << '\n';
    }
}
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy