DNA排序

本文通过一道题目探讨了稳定排序与非稳定排序的区别。作者发现直接使用sort会导致错误答案,而使用stable_sort则能正确解决问题。文章提供了C++实现代码示例,并详细解释了如何通过比较字符串来确定其顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目直接暴力,但是考察了稳定排序和非稳定排序,使用sort直接WA了(不稳定排序),而使用stable_sort就过了(稳定排序)

  1. #include<iostream>
  2. #include<algorithm>
  3. #include<cstring>
  4. #include<cstdio>
  5. usingnamespacestd;
  6. constintmaxn=1005;
  7. intn;
  8. structnode{
  9. charstr[maxn];
  10. intval;
  11. booloperator<(constnode&a)const{
  12. returnval<a.val;
  13. }
  14. }edge[maxn];
  15. voidDeal(intk){
  16. //cout<<len<<endl;
  17. intsum=0;
  18. //cout<<edge[k].str<<endl;
  19. //cout<<n<<endl;
  20. for(inti=0;i<n;++i){
  21. for(intj=i+1;j<n;++j){
  22. if(edge[k].str[i]>edge[k].str[j]){
  23. sum++;
  24. //cout<<"aaaaaaaaaaaaaaaa"<<endl;
  25. }
  26. }
  27. }
  28. edge[k].val=sum;
  29. }
  30. intmain(){
  31. intm;
  32. while(scanf("%d%d",&n,&m)!=EOF){
  33. for(inti=0;i<m;++i){
  34. for(intj=0;j<n;++j){
  35. cin>>edge[i].str[j];
  36. }
  37. //getchar();
  38. edge[i].val=0;
  39. Deal(i);
  40. //cout<<edge[i].val<<endl;
  41. }
  42. stable_sort(edge,edge+m);
  43. for(inti=0;i<m;++i)
  44. cout<<edge[i].str<<endl;
  45. puts("********************");
  46. }
  47. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值