一共三道编程题,难度 << PAT甲级。C++实现
第一题,大概是给一堆的字符串,找出其中的回文字符串,然后按照字典序排列
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int N;
int isReverse(char *str);
int cmp(const void *p1, const void *p2);
int main(){
int i, j = 0, flag = 0;
char str[257];
cin >> N;
char res[N][257];
for(i = 0; i < N; i++){
scanf("%s", str);
flag = isReverse(str);
if(flag){
strcpy(res[j++], str);
}
}
if(j == 0)
cout << "NONE" << endl;
else{
qsort(res, j, 257, cmp);
for(i = 0; i < j; i++)
printf("%s\n", res[i]);
}
return 0;
}
int isReverse(char *str){
int i, j, n;
n = strlen(str);
for(i = 0, j = n - 1; i < j; i++, j--){
if(str[i] != str[j])
return 0;
}
return 1;
}
int cmp(const void *p1, const void *p2) {
char *s1, *s2;
s1 = (char*)p1;
s2 = (char*)p2;
if(strlen(s1) != strlen(s2))
return strlen(s1) - strlen(s2);
else
return strcmp(s1, s2);
}
第二题
给定一个数字,输出这个数字和它的倒序数字的和(输入123,输出123 + 321 )
#include<iostream>
#include<cstring>
using namespace std;
long int char2num(char *s){
int i;
long int res = 0;
for(i = 0; s[i] != 0; i++){
res *= 10;
res += s[i] - '0';
}
return res;
}
void reverse(char * s){
char res[6];
int i, n;
n = strlen(s) - 1;
for(i = 0; n >= 0; n--, i++){
res[i] = s[n];
}
res[i] = 0;
strcpy(s, res);
}
int main(){
long int key;
char s[6];
scanf("%s", s);
key = char2num(s);
//cout << key << endl;
reverse(s);
//cout << s << endl;
key += char2num(s);
cout << key << endl;
return 0;
}
第三题
稍微复杂一点,相当于找一个图中任意两个节点是否在一个环内
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<vector>
using namespace std;
int N, id;
vector< vector<int> > m;
map<string, int> n2i;
int name2id(string name){
map<string, int>::iterator iter;
iter = n2i.find(name);
if(iter == n2i.end()){
n2i.insert(map<string, int>::value_type(name, id++));
vector<int> temp;
m.push_back(temp);
}
return n2i[name];
}
int findpath(int src, int des, vector< vector<int> > m){
int v, i, w;
queue<int> q;
int know[id];
if(src == des)
return 1;
q.push(src);
for(i = 0; i < id; i++)
know[i] = 0;
while(1){
if(q.empty())
break;
v = q.front();
q.pop();
know[v] = 2;
for(i = 0; i < m[v].size(); i++){
w = m[v][i];
if(!know[w]){
if(w == des)
return 1;
q.push(w);
know[w] = 1;
}
}
}
return 0;
}
int findcycle(int src, int des, vector< vector<int> > m){
int res = 0;
res += findpath(src, des, m);
res += findpath(des, src, m);
return res == 2;
}
int main(){
int i, j, k;
string n1, n2;
cin >> N;
map<int, map<int, int> >::iterator iter;
id = 0;
for(i = 0; i < N; i++){
cin >> n1 >> n2;
j = name2id(n1);
k = name2id(n2);
m[j].push_back(k);
}
cin >> n1 >> n2;
j = name2id(n1);
k = name2id(n2);
i = findcycle(j, k, m);
if(i)
cout << "T" << endl;
else
cout << "F" << endl;
return 0;
}