`
saybody
  • 浏览: 870367 次
  • 性别: Icon_minigender_2
  • 来自: 西安
文章分类
社区版块
存档分类
最新评论

程序员12期算法擂台

阅读更多
看了12期的讲解,赶紧回来把代码写出来:
//huiwen.cpp:Definestheentrypointfortheconsoleapplication.
//

#include
"stdafx.h"

voidswap(char*consts,inti,intj)
...{
chartemp;
temp
=s[i];
s[i]
=s[j];
s[j]
=temp;
}

intpseudo_bubble(char*consts,intlength)
...{
inti,j,k;
intodd;
charalphabet[26];
intcount=0;

for(i=0;i<length;i++)
alphabet[s[i]
-'a']++;

odd
=-1;
for(i=0;i<sizeof(alphabet);i++)
if(alphabet[i]%2)...{
if(odd=-1)//thefirst'odd'
odd='a'+i;
else//2odds
return-1;
}


i
=0;
while(s[i]!=s[length-1-i])...{//untilthecorrespondingelementisright
j=length-1-i;
for(k=j-1;k>i&&s[k]!=s[i];k--);//findthecorrespondingelement'slocation
if(k==i)...{//findnobody->thisisthelast'odd'-closesttothecenter
swap(s,k,k+1);
}
else...{
while(k<j)...{
swap(s,k,k
+1);//bubbleitout
count++;
k
++;
}

i
++;
}

}


returncount;
}


int_tmain(intargc,_TCHAR*argv[])
...{
intx;
chars[]=...{'a','b','a','c','a','e','b','a','d','c','d'};
//{'a','b','a','c','a','b','a','d','c','d'};
//{'a','b','a','c','e','b','e','d','c','d'};
x=pseudo_bubble(s,sizeof(s));
if(x==-1)
printf(
"Impossible");
else
printf(
"%d",x);

//getchar();
return0;
}
开的VS2005写的,显得累赘。。。
找奇数次出现的元素所用的循环可以合并到后来的排序的循环里去的,不过那样,太丑。。。
刚看讲解时以为说的是选择成对字符时可以“左右开弓”?? 但做起来似乎代码很麻烦,所以干脆以左半边为准排序。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics