U - Three displays

Problem description

It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.node

There are n displays placed along a road, and the i-th of them can display a text with font size si only. Maria Stepanovna wants to rent such three displays with indices i<j<k that the font size increases if you move along the road in a particular direction. Namely, the condition si<sj<sk should be held.c++

The rent cost is for the i-th display is ci. Please determine the smallest cost Maria Stepanovna should pay.ide

Input

The first line contains a single integer n (3n3000) — the number of displays.spa

The second line contains n integers s1,s2,,sn (1si10^9) — the font sizes on the displays in the order they stand along the road.code

The third line contains n integers c1,c2,,cn (1ci10^8) — the rent costs for each display.xml

Output

If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integer — the minimum total rent cost of three displays with indices i<j<k such that si<sj<sk.blog

Examplesthree

Input

5
2 4 5 4 10
40 30 20 10 40

Output

90

Input

3
100 101 100
2 4 5

Output

-1

Input

10
1 2 3 4 5 6 7 8 9 10
10 13 11 14 15 12 13 13 18 13

Output

33

Noteip

In the first example you can, for example, choose displays 14 and 5, because s1<s4<s5(2<4<10), and the rent cost is 40+10+40=90.ci

In the second example you can't select a valid triple of indices, so the answer is -1.

解題思路:題目的意思就是找出連續遞增的三個數si,sj,sk,使得si<sj<sk,而且使得ci+cj+ck的和最小。作法:從二個數開始循環到倒數第二個數,每循環到當前值sj就向兩邊遍歷查找符合條件的si、sk對應的最小ci,ck值,若是找獲得即m一、m2都≠INF,就將三個c值相加再和原來的最小值mincost進行比較替換;最後若是mincost仍是INF,說明找不到這樣符合條件的狀況,此時輸出"-1"。時間複雜度爲是O(n2),暴力即過。

AC代碼:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int INF=3e8+5;//這裏INF要設置成比3e8大一點,由於三個c值相加有可能恰好爲3e8  4 struct NODE{int s,c;}node[3005];
 5 int main(){
 6     int n,m1,m2,mincost=INF;cin>>n;
 7     for(int i=0;i<n;++i)cin>>node[i].s;
 8     for(int i=0;i<n;++i)cin>>node[i].c;
 9     for(int i=1;i<n-1;++i){
10         m1=m2=INF;
11         for(int j=i-1;j>=0;--j)
12             if(node[j].s<node[i].s&&node[j].c<m1)m1=node[j].c;
13         for(int j=i+1;j<n;++j)
14             if(node[j].s>node[i].s&&node[j].c<m2)m2=node[j].c;
15         if(m1!=INF&&m2!=INF)mincost=min(mincost,node[i].c+m1+m2);
16     }
17     if(mincost<INF)cout<<mincost<<endl;
18     else cout<<"-1"<<endl;
19     return 0;
20 }
相關文章
相關標籤/搜索