算法—会议最大合理安排问题
参考:趣学算法
代码:
# include <stdio.h>
# include <stdlib.h>
typedef struct meet { int beg; int end; int num;
} meet;
int cmp44 ( meet m1, meet m2) { if ( m1. end == m2. end) { if ( m1. beg > m2. beg) { return 1 ; } } else if ( m1. end < m2. end) { return 1 ; } return 0 ;
}
int quickSort ( meet a[ ] , int l, int h) { int i = l, j = h; meet p = a[ l] ; while ( i < j) { while ( i< j&& cmp44 ( p, a[ j] ) ) { j-- ; } if ( i < j) { a[ i++ ] = a[ j] ; } while ( i < j&& cmp44 ( a[ i] , p) ) { i++ ; } if ( i < j) { a[ j-- ] = a[ i] ; } } a[ i] = p; return i;
}
void fenZhi ( meet a[ ] , int l, int h) { if ( l < h) { int mid = quickSort ( a, l, h) ; fenZhi ( a, l, mid - 1 ) ; fenZhi ( a, mid + 1 , h) ; }
}
void meetSelect ( meet Meet[ ] , int n) { int last = Meet[ 0 ] . end; int ans = 0 ; ans++ ; printf ( "选择的会议%d,开始时间为%d,结束时间为%d\n" , Meet[ 0 ] . num, Meet[ 0 ] . beg, Meet[ 0 ] . end) ; for ( int i = 1 ; i < n; i++ ) { if ( Meet[ i] . beg >= last) { ans++ ; last = Meet[ i] . end; printf ( "选择的会议%d,开始时间为%d,结束时间为%d\n" , Meet[ i] . num, Meet[ i] . beg, Meet[ i] . end) ; } } printf ( "会议总数为%d\n" , ans) ;
}
int main ( ) { meet Meet[ 100 ] ; int n; printf ( "输入会议数:" ) ; scanf_s ( "%d" , & n) ; for ( int i = 0 ; i < n; i++ ) { scanf_s ( "%d%d" , & Meet[ i] . beg, & Meet[ i] . end) ; Meet[ i] . num = i + 1 ; } fenZhi ( Meet, 0 , n - 1 ) ; printf ( "会议编号 会议开始时间 会议结束时间\n" ) ; for ( int i = 0 ; i < n; i++ ) { printf ( "%d %d %d\n" , Meet[ i] . num, Meet[ i] . beg, Meet[ i] . end) ; } meetSelect ( Meet, n) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(nlogn),空间复杂度O(1)
如果存在什么问题,欢迎批评指正!谢谢!