拼数--洛谷1012

分析:转化为字符串,然后按照字典序比较全排列,找出最大的

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<cmath>
 6 using namespace std;
 7 const int maxn=22;
 8 string str[maxn];
 9 int a[maxn];
10 int n;
11 string num;
12 void Rev(string &s){
13     int i=0,j=s.length()-1;
14     while(i<j){
15         swap(s[i],s[j]);
16         i++,j--;
17     }
18 }
19 void dfs(int cur){
20     if(cur==n){
21         string p="";
22         for(int i=0;i<n;i++){
23             p+=str[i];
24         }
25         if(p>num){
26             num="";
27             for(int i=0;i<p.length();i++)
28                 num+=p[i];
29         }
30     }
31     for(int i=cur;i<n;i++){
32         if(cur!=i&&str[i]==str[cur])
33             continue;
34         swap(str[i],str[cur]);
35         dfs(cur+1);
36         swap(str[i],str[cur]);
37     }
38 }
39 int main()
40 {
41     while(cin>>n)
42     {
43         for(int i=0;i<n;i++)
44             cin>>a[i];
45         for(int i=0;i<n;i++){
46             string s="";
47             while(a[i]){
48                 s+=a[i]%10+'0';
49                 a[i]/=10;
50             }
51             Rev(s);
52             str[i]=s;
53         }
54         num="";
55         dfs(0);
56         cout<<num<<endl;
57     }
58 }
View Code
原文地址:https://www.cnblogs.com/wolf940509/p/6417125.html