1038. Recover the Smallest Number (30)

经典面试题

以下关于该解法正确性的详细证明转自何海涛的博客:

 

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

bool cmp(string a, string b)
{
	return a+b < b+a;
}

int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		std::vector<string> number(n);
		for(int i = 0; i < n; ++i)
			cin>>number[i];
		//sort
		sort(number.begin(), number.end(), cmp);
		//get the first non-zero
		string ans;
		for(int i = 0; i < n; ++i)
			ans += number[i];
		int non_zero = -1;
		for(int i = 0; i < ans.size(); ++i)
			if(ans[i] != '0')
			{
				non_zero = i;
				break;
			}
		if(non_zero == -1)
			printf("0\n");
		else 
		{
			ans = ans.substr(non_zero);
			cout<<ans<<endl;
		}

	}
	return 0;
}


 

 

你可能感兴趣的:(pat,ZJU)