PAT A1038
還是貪心算法應用;
建立string的數組,輸入之后,兩兩進行比較,a+b>b+a,則兩兩交換位置,將每個string放到合適的位置,從而使得局部最優,變為整體最優;
這里示例代碼使用的是sort函數,個人不太清楚這個機制,但是總的來說,這個題目的string排序和相鄰元素相互比較從而交換的方式相同;
具體代碼如下所示:
#include<iostream> #include<stdlib.h> #include<stdio.h> #include<algorithm> #include<string> using namespace std; const int maxn=10010; string str[maxn]; bool cmp(string a,string b){return a+b<b+a; }int main(){int n;cin>>n;for(int i=0;i<n;i++){cin>>str[i];}sort(str,str+n,cmp);string ans;for(int i=0;i<n;i++){ans+=str[i];}while(ans.size()!=0&&ans[0]=='0'){ans.erase(ans.begin());}if(ans.size()==0)cout<<0;elsecout<<ans;system("pause");return 0; }總結
- 上一篇: GitLab CI/CD 因git凭据踩
- 下一篇: 七、MyBatis教程之四多表关系的实现