目录
1. 1003 我要通过!
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool judge(string s)
{
int i;
int count_p = 0, count_a=0, count_t=0;
int position_p = 0, position_a=0,position_t = 0;
int num1 = 0, num2 = 0, num3 = 0;
for (i = 0; i < s.length(); i++)
{
if (s[i] != 'P'&&s[i] != 'A'&&s[i] != 'T')
return false;
if (s[i] == 'P')
count_p++;
else if (s[i] == 'A')
count_a++;
else if (s[i] == 'T')
count_t++;
}
if (count_p != 1 || count_t != 1 || count_a < 1)
return false;
position_p = s.find('P');
position_a = s.find('A');
position_t = s.find('T');
if (position_p >= position_t)
return false;
for (i = 0; i < s.length(); i++)
{
if (i < position_p&&s[i] == 'A')
num1++;
else if (i > position_p&&i<position_t&&s[i] == 'A')
num2++;
else if (i > position_t&&s[i] == 'A')
num3++;
}
if(num2==0) return false;
else if (num3 == num1 * num2)
return true;
else
return false;
}
int main()
{
int n;
string s;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> s;
if (judge(s)){
if(i!=n-1) cout << "YES"<<endl;
else cout << "YES";
}
else{
if(i!=n-1) cout << "NO"<< endl;
else cout << "NO";
}
}
return 0;
}
2. 1004 成绩排名
复习:结构体数组 struct
sort函数的使用
sort(x,y,cmp)
x:数组名 y:数组长度 cmp:自定义函数
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int n,i;
struct student{
string name,id;
int grade;
};
bool cmp(student a,student b){
return a.grade>b.grade;
}
int main()
{
cin>>n;
student s[n];
for(i=0;i<n;i++){
cin>>s[i].name>>s[i].id>>s[i].grade;
}
sort(s,s+n,cmp);
cout<<s[0].name<<" "<<s[0].id<<endl;
cout<<s[n-1].name<<" "<<s[n-1].id;
return 0;
}
3. 1005 继续(3n+1)猜想
递归函数
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int t[100000];
/*对任何一个正整数 n,如果它是偶数,那么把它砍掉一半;
如果它是奇数,那么把 (3n+1) 砍掉一半。
这样一直反复砍下去,最后一定在某一步得到 n=1。*/
void guess(int a){
if(a==1) return;
else if(a%2==0) {
a/=2;
t[a]++;
guess(a);
}
else{
a=(3*a+1)/2;
t[a]++;
guess(a);
}
}
int main()
{
int n,a[100],b[100],i,c=0;
cin>>n;
for(i=0;i<n;i++){
cin>>a[i];
guess(a[i]);
}
for(i=0;i<n;i++){
if(t[a[i]]==0) b[c++]=a[i];
}
sort(b,b+c,greater<int>());
for(i=0;i<c;i++){
if(i==0) cout<<b[i];
else cout<<" "<<b[i];
}
return 0;
}