【貪心】最大整數/數串
阿新 • • 發佈:2018-11-12
題目描述
設有n個正整數,將他們連線成一排,組成一個最大的多位整數。
如:n=3時,3個整數13,312,343,連成的最大整數為34331213。
如:n=4時,4個整數7,13,4,246連線成的最大整數為7424613。
輸入描述:
有多組測試樣例,每組測試樣例包含兩行,第一行為一個整數N(N<=100),第二行包含N個數(每個數不超過1000,空格分開)。
輸出描述:
每組資料輸出一個表示最大的整數。
#include <iostream> #include <string> using namespace std; int n; string a[101]; string output; int x; void greedy(); int main() { while(cin>>n) { for(int i=0; i<n; i++) { cin>>x; a[i]=to_string(x); } greedy(); cout<<output<<endl; } return 0; } void greedy() { for(int i=0; i<n; i++) { for(int j=i; j<n; j++) { if(a[i]+a[j]<a[j]+a[i]) { swap(a[i],a[j]); } } } output=a[0]; for(int i=1; i<n; i++) { output+=a[i]; } }
【2018/11/8後記】
1、如果codeblocks裡報錯“ 'to_string' was not declared in this scope”,那麼需要開啟Settings-Complier,在這一項後面打勾