[关闭]
@994495jj 2017-07-20T01:44:33.000000Z 字数 3854 阅读 1401

数据结构入门讲座

201707 (ACM)数据结构


参考资料



基本数据结构

  1. vector<int>::iterator it;
  2. for(it=vec.begin();it!=vec.end();it++)
  3. cout<<*it<<endl;
  1. bool Comp(const int &a,const int &b)
  2. {
  3. return a>b;
  4. }
  5. sort(vec.begin(),vec.end(),Comp);

排序

  1. void selection_sort(int array[], int N)
  2. {
  3. for (int i=0; i<N; ++i) // N改為N-1更精準
  4. {
  5. // 從尚未排序的數字當中,找出最小的數字。
  6. // (它也是全部數字當中第i小的數字。)
  7. int min_index = i;
  8. for (int j=i+1; j<N; ++j)
  9. if (array[j] < array[min_index])
  10. min_index = j;
  11. // 把第i小的數字,放在第i個位置。
  12. swap(array[i], array[min_index]);
  13. }
  14. }
  1. void bubble_sort(int array[], int N)
  2. {
  3. for (int i=0; i<N; ++i) // N改為N-1更精準
  4. for (int j=0; j<N-i-1; ++j)
  5. if (array[j] > array[j+1])
  6. swap(array[j], array[j+1]);
  7. }
  1. void bubble_sort(int array[], int N)
  2. {
  3. for (int i=0; i<N; ++i) // N改為N-1更精準
  4. {
  5. bool sorted = true;
  6. for (int j=0; i<N-j-1; ++j)
  7. if (array[j] > array[j+1])
  8. {
  9. swap(array[j], array[j+1]);
  10. sorted = false;
  11. }
  12. if (sorted) return;
  13. }
  14. }
  1. void insertion_sort(int array[], int N)
  2. {
  3. for (int i=2; i<N; ++i)
  4. {
  5. int pivot = array[i];
  6. int j;
  7. for (j=i-1; j>=0; --j)
  8. if (pivot < array[j])
  9. array[j+1] = array[j]; // 先行往右挪
  10. else
  11. break;
  12. array[j+1] = pivot; // 插入
  13. }
  14. }
  1. void counting_sort(int array[], int N)
  2. {
  3. // 歸類並標記
  4. int count[10000] = {0};
  5. for (int i=0; i<N; ++i)
  6. count[ array[i] ]++;
  7. // 計數陣列的索引值大小順序,正是元素大小順序。
  8. for (int i=0, k=0; k<N; ++i)
  9. while (count[i]--)
  10. array[k++] = i;
  11. }
  1. struct Data {int key, data;};
  2. void counting_sort(Data* array[], int N)
  3. {
  4. // 歸類並標記
  5. vector<Data*> count[10000];
  6. for (int i=0; i<N; ++i)
  7. count[ array[i]->key ].push_back( array[i] );
  8. // 索引值的大小順序,剛好也是元素的大小順序。
  9. for (int i=0, k=0; k<N; ++i)
  10. for (int j=0; j<count[i].size(); ++j)
  11. array[k++] = count[i][j];
  12. }
  1. struct Node {
  2. int a,b;
  3. bool operator < (const Node &tmp) const {
  4. if(a==tmp.a) return b<tmp.b;
  5. return a<tmp.a;
  6. }
  7. }

集合

  1. int pre[N];
  2. void init() {
  3. for(int i=0;i<N;++i) pre[i]=i;
  4. }
  5. int find(int x) {
  6. if(x==pre[x]) return x;
  7. return pre[x]=find(pre[x]);
  8. }
  9. void join(int x,int y) {
  10. int fx=find(x);
  11. int fy=find(y);
  12. pre[fx]=fy;
  13. }

优先队列

  1. #include<queue>
  2. priority_queue<int> q;
  3. for(int i=0;i<N;++i) {
  4. q.push_back(a[i]);
  5. cout<<q.top()<<endl;//输出堆中最大的元素
  6. }
  7. q.pop();//弹出堆中最大的元素

线段树


树状数组

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注