【UVa】[401]Palindromes

Problem Description

Loading...

Problem Analysis

It’s really hard to screenshot these UVa problems…
Here’s the code I wrote:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<stdio.h>
#include<string.h>
char Re[]="A   3  HIL JM O   2TUVWXY51SE Z  8 ";
char s[30];
char ex(char c) {
	if(c>='A'&&c<='Z')
		return Re[c-'A'];
	else
		return Re[c-'1'+26];
}
int hui(char* s,int len) {
	int i;
	for(i=0; i<(len+1)/2; i++) {
		if(s[i]!=s[len-i-1])
			return 0;
	}
	return 1;
}
int jing(char* s,int len) {
	int i;
	for(i=0; i<(len+1)/2; i++) {
		if(s[i]!=ex(s[len-i-1]))
			return 0;
	}
	return 1;
}
int main() {
	while(scanf("%s",s)!=EOF) {
		if(hui(s,strlen(s))) {
			if(jing(s,strlen(s)))
				printf("%s -- is a mirrored palindrome.\n\n",s);
			else
				printf("%s -- is a regular palindrome.\n\n",s);
		} else if(jing(s,strlen(s)))
			printf("%s -- is a mirrored string.\n\n",s);
		else
			printf("%s -- is not a palindrome.\n\n",s);
	}
	return 0;
}

At first, I forgot to pass arguments to the last two printf calls, so the program kept terminating for no apparent reason.

Still no warning.

In the end, I found it by using an online compiler…

The book’s standard program:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<stdio.h>
#include<string.h>
#include<ctype.h>
const char* rev="A   3  HIL JM O   2TUVWXY51SE Z  8 ";
const char* msg[]= {"not a palindrome","a regular palindrome","a mirrored string","a mirrored palindrome"};
char r(char ch) {
	if(isalpha(ch))
		return rev[ch-'A'];
	return rev[ch-'0'+25];
}
int main() {
	char s[30];
	while(scanf("%s",s)==1) {
		int len = strlen(s);
		int p=1,m=1;
		for(int i=0; i<(len+1)/2; i++) {
			if(s[i]!=s[len-1-i])
				p=0;
			if(r(s[i])!=s[len-1-i])
				m=0;
		}
		printf("%s -- is %s.\n\n",s,msg[m*2+p]);
		//很有意思的输出方法 竟然通过m*2+p的式子神奇地判定了输出内容 
	}
	return 0;
}

-.- Actually, at first I kept getting WA because I mistyped one word, and I thought there was something wrong with the code…

The gap between me and the experts is that $m*2+p$: because I didn’t use that clever method and wrote three functions for convenience, it got a bit cumbersome.

Still, the idea was quite clear.

A few if/else branches—I don’t know whether I’ll ever be able to make up for this gap in intelligence in this lifetime…

Problem link: Palindromes - UVA 401 - Virtual Judge

PS: Because UVaOJ often won’t open… I think from now on I’ll try to submit these problems on UVa whenever possible, and if that doesn’t work, I’ll find another address.
This is Huazhong University of Science and Technology’s Virtual Judge
Using the latest vjudge system: Virtual Judge ​

Loading...