HDU 4302 贪吃蛇
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 4302 贪吃蛇相关的知识,希望对你有一定的参考价值。
贪吃蛇
Holedox is a small animal which can be considered as one point. It lives in a straight pipe whose length is L. Holedox can only move along the pipe. Cakes may appear anywhere in the pipe, from time to time. When Holedox wants to eat cakes, it always goes to the nearest one and eats it. If there are many pieces of cake in different directions Holedox can choose, Holedox will choose one in the direction which is the direction of its last movement. If there are no cakes present, Holedox just stays where it is.
INPUT
The input consists of several test cases. The first line of the input contains a single integer T (1 <= T <= 10), the number of test cases, followed by the input data for each test case.The first line of each case contains two integers L,n(1<=L,n<=100000), representing the length of the pipe, and the number of events.
The next n lines, each line describes an event. 0 x(0<=x<=L, x is a integer) represents a piece of cake appears in the x position; 1 represent Holedox wants to eat a cake.
In each case, Holedox always starts off at the position 0.
OUTPUT
Output the total distance Holedox will move. Holedox don’t need to return to the position 0.
Sample Input
3
10 8
0 1
0 5
1
0 2
0 0
1
1
1
10 7
0 1
0 5
1
0 2
0 0
1
1
10 8
0 1
0 1
0 5
1
0 2
0 0
1
1
Sample Output
Case 1: 9
Case 2: 4
Case 3: 2
思路:开始尝试使用数组,超时,然后考虑各种数据结构,没错,就是使用优先队列,一下子就AC了。。
//听说网上还有2种做法,一定要去了解一下
#include <iostream> #include <cstring> #include <algorithm> #include <queue> using namespace std; int main() { int t; cin >> t; for(int T = 1; T <= t; T++) { priority_queue<int> s; priority_queue<int, vector<int>, greater<int> > ss; int she = 0; long long sum = 0; int l, n; int fangxiang = 1;//1为右,0为左 cin >> l >> n; while(n--) { int c; cin >> c; if(c == 0) { int x; cin >> x; if(x > she)ss.push(x); else s.push(x); } else { if(!s.empty() && !ss.empty() && ss.top() - she > she - s.top()){sum += she - s.top();she = s.top();fangxiang = 0;s.pop();continue;} if(s.empty() && !ss.empty()){sum += ss.top() - she;she = ss.top();fangxiang = 1;ss.pop();continue;} if(!s.empty() && !ss.empty() &&ss.top() - she < she - s.top()){sum += ss.top() - she;she = ss.top();fangxiang = 1;ss.pop();continue;} if(!s.empty() && ss.empty()){sum += she - s.top();she = s.top();fangxiang = 0;s.pop();continue;} if(!s.empty() && !ss.empty() && ss.top() - she == she - s.top() ) { if(fangxiang == 1) { sum += ss.top() - she; she = ss.top(); ss.pop(); } else { sum += she - s.top(); she = s.top(); s.pop(); } } } } cout << "Case " << T << ": " << sum << endl; } return 0; }
以上是关于HDU 4302 贪吃蛇的主要内容,如果未能解决你的问题,请参考以下文章