CodeForces 510C Fox And Names

Dear 丶 2022-08-19 08:19 239阅读 0赞

一道拓扑排序题!!

注意判断各种情况,两个字符串比较的时候,从左向右开始比较,当出现不同的字母后,不再向后比较。一个是另一个的前缀,那么长的在后面。

当给出的顺序出现环的时候,或者有串的前缀在串的后面时,出现错误。

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<algorithm>
  4. #include<vector>
  5. char a[1001][1001];
  6. int in[10001],v[1001][101],cnt;
  7. char b[1001];
  8. using namespace std;
  9. int topsort()
  10. {
  11. int t1,t2,i,j;
  12. for(i=0;i<26;i++)
  13. {
  14. for(j=0;j<26;j++)
  15. {
  16. if(in[j]==0)
  17. {
  18. t1=j;
  19. in[j]=-1;
  20. break;
  21. }
  22. }
  23. if(j==26)
  24. return 0;
  25. b[cnt++]=j+'a';
  26. for(j=0;j<26;j++)
  27. {
  28. if(v[t1][j])
  29. {
  30. in[j]--;
  31. }
  32. }
  33. }
  34. return 1;
  35. }
  36. int main()
  37. {
  38. int i,j,m,n,l;
  39. while(~scanf("%d",&n))
  40. {
  41. cnt=0;
  42. memset(v,0,sizeof(v));
  43. memset(in,0,sizeof(in));
  44. for(i=0;i<n;i++)
  45. {
  46. scanf("%s",a[i]);
  47. }
  48. for(i=0;i<n-1;i++)
  49. {
  50. int f=0;
  51. int l1=strlen(a[i]);
  52. int l2=strlen(a[i+1]);
  53. for(j=0;j<min(l1,l2);j++)
  54. {
  55. if(a[i][j]!=a[i+1][j])
  56. {
  57. f=1;
  58. int t1=a[i][j]-'a';
  59. int t2=a[i+1][j]-'a';
  60. if(!v[t1][t2])
  61. {
  62. in[t2]++;
  63. v[t1][t2]=1;
  64. }
  65. break;
  66. }
  67. }
  68. if(l2<l1&&f==0)
  69. {
  70. printf("Impossible\n");
  71. return 0;
  72. }
  73. }
  74. if(topsort())
  75. puts(b);
  76. else
  77. puts("Impossible");
  78. }
  79. return 0;
  80. }

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读

    相关 510-C++问题总结(1)

    1、C++this指针干什么用的? 1个类型定义的对象都有各自的成员变量,但是是共享一套成员方法,在成员方法里,是访问谁的成员变量,这个是靠this指针区分的。1个类型定义

    相关 CodeForces 510C Fox And Names

    一道拓扑排序题!! 注意判断各种情况,两个字符串比较的时候,从左向右开始比较,当出现不同的字母后,不再向后比较。一个是另一个的前缀,那么长的在后面。 当给出的顺序出现环的时