There are NN pieces of sushi. Each piece has two parameters: "kind of topping" titi and "deliciousness" didi. You are choosing KK among these NN pieces to eat. Your "satisfaction" here will be calculated as follows:html
You want to have as much satisfaction as possible. Find this maximum satisfaction.c++
Input is given from Standard Input in the following format:this
NN KK t1t1 d1d1 t2t2 d2d2 .. .. .. tNtN dNdN
Print the maximum satisfaction that you can obtain.spa
5 3 1 9 1 7 2 6 2 5 3 1
26
If you eat Sushi 1,21,2 and 33:code
Thus, your satisfaction will be 2626, which is optimal.orm
7 4 1 1 2 1 3 1 4 6 4 5 4 5 4 5
25
It is optimal to eat Sushi 1,2,31,2,3 and 44.xml
6 5 5 1000000000 2 990000000 3 980000000 6 970000000 6 960000000 4 950000000
4900000016
Note that the output may not fit into a 3232-bit integer type.htm
題意:給定N個結構體,每個結構體有兩個信息,分別是type 和 x,讓你從中選出K個結構體,使之type的類型數的平方+sum{ xi } 最大。blog
思路:【貪心】將X從大到小排序,而後按順序取前K個,在取前K個過程當中,將已經出現的類型放入棧中。而後,開始遍歷K+1----N的元素,使得不斷加入沒有出現的元素的類型。在此過程當中經過彈棧更新最值。排序
AC代碼:
1 #include<bits/stdc++.h> 2 3 using namespace std; 4 #define int long long 5 #define N 150000 6 struct str{ 7 int x,y; 8 }st[N]; 9 bool cmp(str a,str b){ 10 return a.y>b.y; 11 } 12 map<int,int> mp; 13 stack<int> s; 14 signed main(){ 15 int n,k; 16 cin>>n>>k; 17 for(int i=1;i<=n;i++){ 18 cin>>st[i].x>>st[i].y; 19 } 20 sort(st+1,st+1+n,cmp); 21 int maxn=0; 22 int type=0; 23 int sum=0; 24 for(int i=1;i<=k;i++){ 25 if(!mp[st[i].x]){ 26 mp[st[i].x]=1; 27 type++; 28 }else{ 29 s.push(st[i].y); 30 } 31 sum+=st[i].y; 32 maxn=max(maxn,type*type+sum); 33 } 34 for(int i=k+1;i<=n;i++){ 35 if(s.empty()) 36 break; 37 if(mp[st[i].x]) 38 continue; 39 mp[st[i].x]=1; 40 type++; 41 sum-=s.top(); 42 s.pop(); 43 sum+=st[i].y; 44 maxn=max(maxn,type*type+sum); 45 } 46 cout<<maxn; 47 return 0; 48 }