HDU 3415(単調キュー)

8468 ワード

Max Sum of Max-K-sub-sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4080 Accepted Submission(s): 1453
Problem Description
Given a circle sequence A[1],A[2],A[3]......A[n]. Circle sequence means the left neighbour of A[1] is A[n] , and the right neighbour of A[n] is A[1].
Now your job is to calculate the max sum of a Max-K-sub-sequence. Max-K-sub-sequence means a continuous non-empty sub-sequence which length not exceed K.
 
 
Input
The first line of the input contains an integer T(1<=T<=100) which means the number of test cases.
Then T lines follow, each line starts with two integers N , K(1<=N<=100000 , 1<=K<=N), then N integers followed(all the integers are between -1000 and 1000).
 
 
Output
For each test case, you should output a line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the minimum start position, if still more than one , output the minimum length of them.
 
 
Sample Input
4 6 3 6 -1 2 -6 5 -5 6 4 6 -1 2 -6 5 -5 6 3 -1 2 -6 5 -5 6 6 6 -1 -1 -1 -1 -1 -1
 
 
Sample Output
7 1 3 7 1 3 7 6 2 -1 1 1
 1 /*

 2     :     N   (N<=10^5)     ,              。              K。

 3  4 */

 5 #include<iostream>

 6 #include<queue>

 7 using namespace std;

 8 

 9 const int INF = 0x3fffffff;

10 const int maxn = 100010;

11 int num[maxn],sum[maxn];

12 

13 int main()

14 {

15     int T,i,j;

16     int N,K,n;

17     cin>>T;

18     while(T--)

19     {

20         cin>>N>>K;

21         sum[0]=0;

22         for(i=1;i<=N;i++)

23         {

24             cin>>num[i];

25             sum[i]=sum[i-1]+num[i];

26         }

27         for(i=N+1;i<N+K;i++)

28         {

29             sum[i]=sum[i-1]+num[i-N];

30         }

31         n=N+K-1; 

32         deque <int> q;

33         q.clear();

34         int ans=-INF;

35         int start,end;

36         //   j     

37         for(j=1;j<=n;j++)

38         {

39             while(!q.empty() && sum[j-1]<sum[q.back()])

40                 q.pop_back();

41             while(!q.empty() && q.front()<(j-K))//       K ,    ,       (j-1)

42                 q.pop_front();

43             q.push_back(j-1);

44             if(sum[j]-sum[q.front()]>ans)

45             {

46                 ans=sum[j]-sum[q.front()];

47        //i j  ,sum[8] - sum[5] = sum[6]+sum[7]+sum[8]



       start=q.front()+1; 48 end=j; 49 } 50 } 51 cout<<ans<<" "<<start<<" "<<(end>N?end%N:end)<<endl; 52 } 53 return 0; 54 }
////