1861解题报告

来源:互联网 发布:2010excel矩阵相乘 编辑:程序博客网 时间:2024/03/29 14:44

AccecptTime:      2008-12-17 12:40:01
Language:             c++
Memory:              384K
Time:                    94MS
Errors:                  3 WA + 1 RE + 3 TLE
Algorithm:            并查集 + sort()

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. // 以下是sort()用到的stl
  4. #include <algorithm>
  5. using namespace std;
  6. typedef struct {
  7.     int x;
  8.     int y;
  9.     int lenght;
  10. } pipeType;
  11. pipeType pipe[15005];
  12. int parent[1005];
  13. // 结构体的比较函数
  14. struct pt_cmp
  15. {
  16. bool operator () ( const pipeType &a, const pipeType &b ) const 
  17. {
  18.     return a.lenght < b.lenght;
  19. }
  20. };
  21. //找父节点并对路径进行压缩
  22. int FindParent(int x)
  23. {
  24.     if( parent[x] != x) 
  25.         parent[x] = FindParent(parent[x]);
  26.     return parent[x];
  27. }
  28. void MergeSet(int x,int y)
  29. {
  30.     if( x > y)
  31.         parent[y] = x;
  32.     else
  33.         parent[x] = y;
  34. }
  35. int main()
  36. {
  37.     int n,d,count = 0;
  38.     int t1,t2, i;
  39.     int max, sum = 0;
  40.     scanf("%d%d",&n,&d);
  41.     for( i = 1; i <= n; i++)
  42.         parent[i] = i;
  43.     for( i = 0; i < d; i++)
  44.         scanf("%d%d%d",&(pipe[i].x), &(pipe[i].y), &(pipe[i].lenght));
  45.     //由于qsort() 的不稳定性 这里使用 sort() 来代替
  46.     sort(pipe,pipe + d,pt_cmp());
  47.     for( i = 0; i < d && count < (n - 1); i++) {
  48.         t1 = FindParent(pipe[i].x);
  49.         t2 = FindParent(pipe[i].y);
  50.         if( t1 != t2)  {
  51.             count++;
  52.             MergeSet(t1,t2);
  53.         }
  54.         max = pipe[i].lenght;
  55.     }
  56.     printf("%d/n%d/n",max,i);
  57.     for(int j = 0; j < i ; j++)
  58.         if(pipe[j].x != pipe[j].y)
  59.             printf("%d %d/n",pipe[j].x,pipe[j].y);
  60. }

这道题的算法并不难,重点是对排序的应用,有时候你必须通过其他类型的排序以满足某些条件,如这次用sort() 来保持数组的稳定性(即长度一样的管的先后顺序不变),而另外一道题则需要用MergeSort()来计算数组的逆序数。这题wa了3次有两次是因为没用sort()导致数组不稳定,一次是因为低级的逻辑错误,一次CE是因为改了以后连example都没过就交了,后来的LTE也是因为没使用sort()。这是sort的一次应用,以后可能还会用到

原创粉丝点击