AccecptTime: 2008-12-17 12:40:01
Language: c++
Memory: 384K
Time: 94MS
Errors: 3 WA + 1 RE + 3 TLE
Algorithm: 并查集 + sort()
- #include <stdio.h>
- #include <stdlib.h>
- // 以下是sort()用到的stl
- #include <algorithm>
- using namespace std;
- typedef struct {
- int x;
- int y;
- int lenght;
- } pipeType;
- pipeType pipe[15005];
- int parent[1005];
- // 结构体的比较函数
- struct pt_cmp
- {
- bool operator () ( const pipeType &a, const pipeType &b ) const
- {
- return a.lenght < b.lenght;
- }
- };
- //找父节点并对路径进行压缩
- int FindParent(int x)
- {
- if( parent[x] != x)
- parent[x] = FindParent(parent[x]);
- return parent[x];
- }
- void MergeSet(int x,int y)
- {
- if( x > y)
- parent[y] = x;
- else
- parent[x] = y;
- }
- int main()
- {
- int n,d,count = 0;
- int t1,t2, i;
- int max, sum = 0;
- scanf("%d%d",&n,&d);
- for( i = 1; i <= n; i++)
- parent[i] = i;
- for( i = 0; i < d; i++)
- scanf("%d%d%d",&(pipe[i].x), &(pipe[i].y), &(pipe[i].lenght));
- //由于qsort() 的不稳定性 这里使用 sort() 来代替
- sort(pipe,pipe + d,pt_cmp());
- for( i = 0; i < d && count < (n - 1); i++) {
- t1 = FindParent(pipe[i].x);
- t2 = FindParent(pipe[i].y);
- if( t1 != t2) {
- count++;
- MergeSet(t1,t2);
- }
- max = pipe[i].lenght;
- }
- printf("%d/n%d/n",max,i);
- for(int j = 0; j < i ; j++)
- if(pipe[j].x != pipe[j].y)
- printf("%d %d/n",pipe[j].x,pipe[j].y);
- }
这道题的算法并不难,重点是对排序的应用,有时候你必须通过其他类型的排序以满足某些条件,如这次用sort() 来保持数组的稳定性(即长度一样的管的先后顺序不变),而另外一道题则需要用MergeSort()来计算数组的逆序数。这题wa了3次有两次是因为没用sort()导致数组不稳定,一次是因为低级的逻辑错误,一次CE是因为改了以后连example都没过就交了,后来的LTE也是因为没使用sort()。这是sort的一次应用,以后可能还会用到