sicily 1198

錯誤寫法:貪心算法

•先對N個字符串按字典序排序
•後從小到大拼在一起
•如:a ac ab 排序後就是 a ab ac
•最後的字符串即是 aabac
•又如:b ac bd abc 排序後是 abc ac b bd
•最後的字符串即是 abcacbbd
•但是,這個是錯誤的!
•反例:b ba
•bba?
•bab!
正確寫法爲:
#include "iostream"
#include "algorithm"
#include"string"
using namespace std;
bool cmp(string s1,string s2){

	return s1+s2 <s2+s1; //這是這個題目的關鍵
}

int main()
{
	int T,n;
	cin>>T;
	while (T--)
	{
		cin>>n;
		string *str = new string[n];
		string result;
		//輸入
		for (int i = 0;i < n;i++)
		{
			cin>>str[i];
		}
		sort(str,str + n,cmp);//全排列	
		for (int i = 0;i < n;i++)
		{
			result += str[i];
		}
		cout<<result<<endl;
	}
	//system("pause");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章