1. 程式人生 > >ACM 2018 北京區域賽 I - Palindromes (找規律)

ACM 2018 北京區域賽 I - Palindromes (找規律)

HihoCoder - 1878

題目大意:

       給出k,讓求出第k個迴文數(k的“長度”不超過1e5)

題解:

       真是一道給人警醒的題目

       誰說資料範圍大就要用Java!還有可能是找規律!

       隊友寫java,構造,寫了四個小時。

       如果我也去一起看I題,如果我能質疑一下他們的思路,自己找規律看一下。。。。。。誒

 

     打表仔細耐心看一下是可以發現規律的

     ①對於個位數和10,11就特判一下

      ②然後對於首個數字不是1的k,它對應的迴文串就是將首數字減一,在反轉順序貼到後面

            如k=523,則它對應的迴文串就是42324

          (注意,這種情況下,一定是將0-len-1位反轉貼到後面,即中間要留一個)

      ③對於首個數字是1的k,是將它的首數字1直接拋棄,選取第2-len位

             如果第2位數字不是0,就是將2-len位反轉後貼到後面

            如果第2位數字是0,先將0替換成9,再將2~len-1位反轉後貼到後面(即這時中間要留一個)

#include <bits/stdc++.h>
#include <cstring>
#include<string>
using namespace std;
#define ll long long
int main()
{
    int T,len;
    string s,t,tt;
    cin>>T;
    while(T--)
    {
        cin>>s;
        len=s.length();
        if(len==1 || s=="11" || s=="10")
        {
            if(s=="11")
                puts("11");
            else if(s=="10")
                puts("9");
            else
                cout<<(char)(s[0]-1)<<endl;
            continue;
        }
        if(s[0]=='1')
        {
            if(s[1]=='0')
            {
                s[1]='9';
                s=s.substr(1,len-1);
                t=s.substr(0,len-2);
                reverse(t.begin(),t.end());
                s+=t;
                cout<<s<<endl;
            }
            else
            {
                s=s.substr(1,len-1);
                t=s;
                reverse(t.begin(),t.end());
                s+=t;
                cout<<s<<endl;

            }
            continue;
        }
        s[0]-=1;
        t=s.substr(0,len-1);
        reverse(t.begin(),t.end());
        s+=t;
        cout<<s<<endl;
    }
    return 0;
}

打表程式

#include <bits/stdc++.h>
#include <cstring>
#include<string>
#include<cstdio>
#include<cstdlib>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#define ll long long
bool pd(ll x)
{
    ostringstream oss;
    oss<<x;
    string s=oss.str();
    int len=s.length();
    for(int i=0; i<len/2; ++i)
        if(s[i]!=s[len-i-1])
            return 0;
    return 1;
}
int main()
{
    //freopen("output.txt","w",stdout);
    ll cnt=0;
    for(ll i=0; i<=100000000000000000; ++i)
        if(pd(i))
            cout<<i<<"------"<<++cnt<<endl;
    return 0;
}