USACO section 1.2.4 Dual Palindromes

1. 直接用了上道题的函数,另外,进制转换:

string trans(int a)
{
    string str1 = "";
    int tmp;
    while (a)
    {
        tmp = a % base;
        if (tmp < 10)
            str1 += tmp + '0';
        else
            str1 += tmp - 10 + 'A';
        a /= base;
    }
    return str1;
}


2. 我的代码:

/*
ID: dollar4
PROG: dualpal
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstring>

using namespace std;
int n, s;
bool checkp(string str)
{
    int len = str.size();
    for (int i = 0; i < len; i++)
    {
        if (str[i] != str[len-1-i])
            return false;
    }
    return true;
}
string trans(int a, int b)
{
    string str1 = "";
    int tmp;
    while (a)
    {
        tmp = a % b;
            str1 += tmp + '0';
        a /= b;
    }
    return str1;
}
int main()
{
    ofstream fout ("dualpal.out");
    ifstream fin ("dualpal.in");
    int cnt = 0, i, tmp, j;
    string str;
    fin >> n >> s;
    for (i = s + 1; cnt != n; i++)
    {
        tmp = 0;
        for (j = 2; j < 11; j++)
        {
            str = trans(i, j);
            if (checkp(str))
                tmp++;
            if (tmp >= 2)
            {
                fout << i << endl;
                cnt++;
                break;
            }
        }
    }
    return 0;
}

3. 官方参考代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/* is string s a palindrome? */
int
ispal(char *s)
{
    char *t;

    t = s+strlen(s)-1;
    for(t=s+strlen(s)-1; s<t; s++, t--)
	if(*s != *t)
	    return 0;

    return 1;
}

/* put the base b representation of n into s: 0 is represented by "" */
char*
numbconv(char *s, int n, int b)
{
    int len;

    if(n == 0) {
	strcpy(s, "");
	return s;
    }

    /* figure out first n-1 digits */
    numbconv(s, n/b, b);

    /* add last digit */
    len = strlen(s);
    s[len] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n%b];
    s[len+1] = '\0';
    return s;
}

/* is number n a dual palindrome? */
int
isdualpal(int n)
{
    int i, j, npal;
    char s[40];

    npal = 0;
    for(i=2; i<=10; i++)
	if(ispal(numbconv(s, n, i)))
	    npal++;

    return npal >= 2;
}

void
main(void)
{
    FILE *fin, *fout;
    int n, s;

    fin = fopen("dualpal.in", "r");
    fout = fopen("dualpal.out", "w");
    assert(fin != NULL && fout != NULL);

    fscanf(fin, "%d %d", &n, &s);

    for(s++; n>0; s++) {
	if(isdualpal(s)) {
	    fprintf(fout, "%d\n", s);
	    n--;
	}
    }

    exit(0);
}




posted on 2012-04-11 10:17  赵乐ACM 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/dollarzhaole/archive/2012/04/11/3188920.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值