PAT第三天
1005 Spell It Right
1.以下代码有两个错误提交,考虑到可能是整形溢出
#include<iostream>
#include<cstring>
using namespace std;
int main(){
int n;cin>>n;
int sum=0;
while(n){
sum +=n%10;
n=n/10;
}
string cur[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int k=0;
string ans="";
k=sum%10;
ans +=cur[k];
while(sum/10){
ans =" "+ans;
sum /=10;
k=sum%10;
ans =cur[k]+ans;
}
cout<<ans;
return 0;
}
2.正确做法
#include<iostream>
#include<cctype>
using namespace std;
string cur[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int main(){
int sum=0;
char c;
while(isdigit(c=getchar())){
sum+=c-'0';
}
string temp=to_string(sum);
for(int i=0;i<temp.size();i++){
if(i)cout<<' ';
cout<<cur[temp[i]-'0'];
}
return 0;
}
1006 Sign In and Sign Out
#include <iostream>
#include <climits>
using namespace std;
int main() {
int n, minn = INT_MAX, maxn = INT_MIN;
scanf("%d", &n);
string unlocked, locked;
for(int i = 0; i < n; i++) {
string t;
cin >> t;
int h1, m1, s1, h2, m2, s2;
scanf("%d:%d:%d %d:%d:%d", &h1, &m1, &s1, &h2, &m2, &s2);
int tempIn = h1 * 3600 + m1 * 60 + s1;
int tempOut = h2 * 3600 + m2 * 60 + s2;
if (tempIn < minn) {
minn = tempIn;
unlocked = t;
}
if (tempOut > maxn) {
maxn = tempOut;
locked = t;
}
}
cout << unlocked << " " << locked;
return 0;
}
1007 Maximum Subsequence Sum
解题思路:利用前缀和+双指针
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;cin>>n;
int dp[n],dp2[n],sum=-1,first=0,second=0,low=0;
for(int i=0;i<n;i++){
cin>>dp[i];
if(!i){
dp2[i]=dp[i];
}
else{
dp2[i]=dp2[i-1]+dp[i];
}
}
if(n==1){
sum=dp[0];
first=dp[0];
second=dp[0];
}
else{
for(int end=1;end<n;end++){
if(dp2[end]-dp2[low]>sum){
sum=dp2[end]-dp2[low];
first=dp[low+1];
second=dp[end];
}
if(dp2[low]>dp2[end])low=end;
}
}
if(sum<0)cout<<0<<' '<<dp[0]<<' '<<dp[n-1];
else cout<<sum<<' '<<first<<' '<<second;
return 0;
}
1008 Elevator
解题思路:简单模拟
#include<iostream>
using namespace std;
int main(){
int n,cur=0,ans=0,k;cin>>n;
while(n--){
cin>>k;
if(k>cur)ans +=(k-cur)*6+5;
else if(k<cur) ans +=(cur-k)*4+5;
else ans +=5;
cur=k;
}
cout<<ans;
return 0;
}
浙公网安备 33010602011771号