HDU1106:排序

輸入一行數字,如果我們把這行數字中的‘5’都看成空格,那麼就得到一行用空格分割的若干非負整數(可能有些整數以‘0’開頭,這些頭部的‘0’應該被忽略掉,除非這個整數就是由若干個‘0’組成的,這時這個整數就是0)。

你的任務是:對這些分割得到的整數,依從小到大的順序排序輸出。

Input 輸入包含多組測試用例,每組輸入數據只有一行數字(數字之間沒有空格),這行數字的長度不大於1000。  

輸入數據保證:分割得到的非負整數不會大於100000000;輸入數據不可能全由‘5’組成。
Output 對於每個測試用例,輸出分割得到的整數排序的結果,相鄰的兩個整數之間用一個空格分開,每組輸出佔一行。
Sample Input
0051231232050775
Sample Output

0 77 12312320

一道簡單的模擬題,他說什麼我們做什麼就行了,關鍵點就是把分割串變成整形數字的過程吧,用一些語法技巧的話代碼會好寫得多。我第一次寫用的是string(我只會簡單操作orz),後來觀摩了別人的較短代碼用了strtok函數,照貓畫虎學習了一下。對於string的操作、stringstream、strtok及atoi不太瞭解的同學可以百度並實現一下,不是很難懂。

代碼如下:

0ms的string代碼:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<sstream>
#include<algorithm>
using namespace std;

int r[1001],cnt;
string s;

int a(string s)//字符串變數字 
{
	stringstream ss(s);
	int x;
	ss>>x;
	return x;
}
int main()
{
	while(cin>>s)
	{
		cnt=0;//記錄最後結果的整數的數量 
		memset(r,0,sizeof(r));
		s+='5';
		string t;
		while(s.length())
		{
			t=s.substr(0,s.find('5'));
			if(t.length())
			{
				r[cnt++]=a(t);
				s.erase(0,t.length());
			}
			
			while(s[0]=='5'&&s.length())
				s.erase(0,1);
		} 
		
		sort(r,r+cnt);
		for(int i=0;i<cnt;i++)
			printf("%d%c",r[i],i==cnt-1?'\n':' ');
	}
	return 0;
}

15ms的strtok代碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm> 
using namespace std;

int main()
{
	char str[1005];
	while(~scanf("%s",str))
	{
		int cnt=0,a[1005];
		char *p=strtok(str,"5");//strtok爲分裂字符串函數 ,第二個元素按照語法要寫雙引號代表字符串 
		
		while(p!=NULL)
			a[cnt++]=atoi(p),p=strtok(NULL,"5");//分裂以後的首地址就是NULL了 
				
		sort(a,a+cnt);
		for(int i=0;i<cnt;i++)
			printf("%d%c",a[i],i==cnt-1?'\n':' ');	
	}
	return 0;
}

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