贪心算法实例

来源:互联网 发布:f117和f22 知乎 编辑:程序博客网 时间:2024/05/01 23:38

     最近看到了一个好的程序

    题目是这样的:输入几个数字,然后连接起来组成一个最大数!

   比如你输入 540 ,21, 7, 8,然后就输出了8754021这个数!

   附上代码

#include<iostream>using namespace std;#include<string>#define MAX 50int main(){int n;   while(cin>>n)   {string str[MAX];string  s1,s2;string temp;for(int i=0;i<n;i++)//输入字符串数字    cin>>str[i];for(int j=1;j<n;j++)//类似与冒泡程序代码  for(int m=0;m<n-j;m++)   {  s1=str[m]+str[m+1];  s2=str[m+1]+str[m];    if(s1<s2)//交换两个位置   {    temp=str[m];    str[m]=str[m+1];    str[m+1]=temp;  }    }   for(int v=0;v<n;v++)//选择输出字符串      cout<<str[v];     cout<<endl;   } return 0;}
点滴的积累,才能成就自我!

0 0
原创粉丝点击