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
The first line contains a single integer n (3≤n≤3000) — the number of displays.spa
The second line contains n integers s1,s2,…,sn (1≤si≤10^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 (1≤ci≤10^8) — the rent costs for each display.xml
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
5
2 4 5 4 10
40 30 20 10 40
90
3
100 101 100
2 4 5
-1
10
1 2 3 4 5 6 7 8 9 10
10 13 11 14 15 12 13 13 18 13
33
Noteip
In the first example you can, for example, choose displays 1, 4 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 }