生活随笔
收集整理的這篇文章主要介紹了
第 2 章:初出茅庐【初级篇 - 2.2 贪心算法】
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
- 206. 硬幣問題 II【簡單】
- 212. 區(qū)間調(diào)度問題【常見模型】
- 213. 字典序最小問題 Best Cow Line【有意思的模型】
- 214. 薩魯曼的軍隊(duì) Saruman's Army【常見的模型】
- 217. 柵欄修理 Fence Repair【常見模型】
206. 硬幣問題 II【簡單】
https://www.papamelon.com/problem/206
顯而易見的是先用面值大的鈔票。
#include<bits/stdc++.h>
using namespace std
;
int a
[10],t
,n
,m
;
int b
[10]={1,5,10,50,100,500};
int main(void)
{cin
>>t
;while(t
--){for(int i
=0;i
<6;i
++) cin
>>a
[i
];cin
>>m
;int cnt
=0;for(int i
=5;i
>=0;i
--){int temp
=min(m
/b
[i
],a
[i
]);m
-=b
[i
]*temp
,cnt
+=temp
;}cout
<<cnt
<<endl
;}
}
212. 區(qū)間調(diào)度問題【常見模型】
https://www.papamelon.com/problem/212
按照右端點(diǎn)排序。越早選,越早結(jié)束。因?yàn)槲覀兊挠叶它c(diǎn)是從小到大排序的。
#include<bits/stdc++.h>
using namespace std
;
int n
,l
,r
;
int main(void)
{while(cin
>>n
){vector
<pair
<int,int>>ve
;for(int i
=0;i
<n
;i
++){cin
>>l
>>r
;ve
.push_back({r
,l
});}sort(ve
.begin(),ve
.end());int cnt
=1;r
=ve
[0].first
;for(int i
=1;i
<ve
.size();i
++){if(ve
[i
].second
>r
){cnt
++;r
=ve
[i
].first
;}}cout
<<cnt
<<'\n';}return 0;
}
213. 字典序最小問題 Best Cow Line【有意思的模型】
https://www.papamelon.com/problem/213
本題的關(guān)鍵難點(diǎn)在于,當(dāng)頭尾相同的時(shí)候該如何選。
我們需要特別的判斷,其剩余字符串正和反的哪個(gè)更優(yōu)。
#include<bits/stdc++.h>
using namespace std
;
const int N
=1e5+10;
int n
;
char c
;
string s
,ans
;
bool cmp(int l
,int r
)
{string s1
=s
.substr(l
,r
-l
+1); string s2
=s1
;reverse(s2
.begin(),s2
.end());if(s1
<=s2
) return true;else return false;
}
int main(void)
{cin
>>n
;for(int i
=0;i
<n
;i
++) cin
>>c
,s
+=c
;int l
=0,r
=n
-1;while(l
<=r
){if(s
[l
]<s
[r
]) ans
+=s
[l
],l
++;else if(s
[r
]<s
[l
]) ans
+=s
[r
],r
--;else {if(cmp(l
,r
)) ans
+=s
[l
],l
++;else ans
+=s
[r
],r
--;}}int cnt
=0;for(int i
=0;i
<ans
.size();i
++){cout
<<ans
[i
];cnt
++;if(cnt
%80==0) cout
<<endl
;}return 0;
}
214. 薩魯曼的軍隊(duì) Saruman’s Army【常見的模型】
https://www.papamelon.com/problem/214
#include<bits/stdc++.h>
using namespace std
;
int r
,n
,x
;
int main(void)
{while(cin
>>r
>>n
,r
!=-1||n
!=-1){vector
<int>ve
;for(int i
=0;i
<n
;i
++) cin
>>x
,ve
.push_back(x
);sort(ve
.begin(),ve
.end());ve
.erase(unique(ve
.begin(),ve
.end()),ve
.end());int cnt
=0;for(int i
=0;i
<ve
.size();i
++){int j
=i
;int len
=ve
[i
]+r
;while(j
+1<ve
.size()&&ve
[j
+1]<=len
) j
++;len
=ve
[j
]+r
;while(j
+1<ve
.size()&&ve
[j
+1]<=len
) j
++;cnt
++;i
=j
;}cout
<<cnt
<<endl
;}return 0;
}
217. 柵欄修理 Fence Repair【常見模型】
https://www.papamelon.com/problem/217
切和合并本質(zhì)是同一種。就是一個(gè)典型的哈夫曼樹。
#include<bits/stdc++.h>
using namespace std
;
typedef long long int LL
;
LL n
,x
,sum
;
priority_queue
<LL
,vector
<LL
>,greater
<LL
>>heap
;
int main(void)
{cin
>>n
;while(n
--) cin
>>x
,heap
.push(x
);while(heap
.size()>1){auto a
=heap
.top(); heap
.pop();auto b
=heap
.top(); heap
.pop();sum
+=a
+b
;heap
.push(a
+b
); }cout
<<sum
;return 0;
}
總結(jié)
以上是生活随笔為你收集整理的第 2 章:初出茅庐【初级篇 - 2.2 贪心算法】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。