haha,貪心,邊界條件折騰了我一會兒 1 #include 2 #include 3 #include 4 #include 5 using namespace std ; 6 7 const int MAXN = 1000000 + 200 ; 8 int N , K ; 9 int dis ....
haha,貪心,邊界條件折騰了我一會兒
1 #include<cstdio> 2 #include<cctype> 3 #include<queue> 4 #include<algorithm> 5 using namespace std ; 6 7 const int MAXN = 1000000 + 200 ; 8 int N , K ; 9 int dis [ MAXN ] ; 10 int l [ MAXN ] ; 11 int r [ MAXN ] ; 12 int v [ MAXN ] ; 13 int vis [ MAXN ] ; 14 int ans ; 15 struct cmp { 16 bool operator () ( const int a , const int b ) { return v [ a ] > v [ b ] ; } ; 17 } ; 18 priority_queue < int , vector < int > , cmp > q ; 19 20 int main () { 21 scanf ( "%d%d" , & N , & K ) ; 22 for ( int i = 1 ; i <= N ; ++ i ) scanf ( "%d" , dis + i ) ; 23 for ( int i = 1 ; i < N ; ++ i ) v [ i ] = dis [ i + 1 ] - dis [ i ] ; 24 for ( int i = 1 ; i < N - 1 ; ++ i ) r [ i ] = i + 1 ; 25 for ( int i = 2 ; i < N ; ++ i ) l [ i ] = i - 1 ; 26 for ( int i = 1 ; i < N ; ++ i ) q . push ( i ) ; 27 fill_n ( vis + 1 , N , 1 ) ; 28 v [ 0 ] = 1000000000 + 1 ; 29 v [ N ] = 1000000000 + 1; 30 while ( K -- ) { 31 while ( ! vis [ q . top () ] ) q . pop () ; 32 const int o = q . top () ; q . pop () ; 33 ans += v [ o ] ; 34 vis [ l [ o ] ] = 0 ; 35 vis [ r [ o ] ] = 0 ; 36 v [ o ] = v [ l [ o ] ] + v [ r [ o ] ] - v [ o ] ; 37 q . push ( o ) ; 38 l [ o ] = l [ l [ o ] ] ; r [ o ] = r [ r [ o ] ] ; 39 r [ l [ o ] ] = l [ r [ o ] ] = o ; 40 } 41 printf ( "%d\n" , ans ) ; 42 }