【hihocoder - offer编程练习赛60 B】最大顺子(双指针,思维)
題干:
時(shí)間限制:10000ms
單點(diǎn)時(shí)限:1000ms
內(nèi)存限制:256MB
描述
你有N張卡片,每張卡片上寫(xiě)著一個(gè)正整數(shù)Ai,并且N張卡片上的整數(shù)各不相同。 ?
此外,你還有M張百搭卡片,可以當(dāng)作寫(xiě)著任意正整數(shù)的卡片。
一個(gè)“順子”包含K張卡片,并且滿足卡片上的整數(shù)恰好是連續(xù)的K個(gè)正整數(shù)。我們將其中最大的整數(shù)稱作順子的值。
例如1-2-3-4-5的值是5,101-102-103的值是103。 ?
請(qǐng)你計(jì)算用給定的N張卡片和M張百搭卡片,能湊出的值最大的順子是多少,并且輸出該順子的值。
輸入
第一行包含3個(gè)整數(shù),N,M和K。 ?
第二行包含N個(gè)整數(shù),A1, A2, ... AN。 ?
對(duì)于50%的數(shù)據(jù),1 ≤ N, K ≤ 1000 ?
對(duì)于100%的數(shù)據(jù),1 ≤ N, K ≤ 100000 0 ≤ M < K 0?≤?Ai?≤?100000000
輸出
一個(gè)整數(shù)代表答案
樣例輸入
10 1 5 1 4 2 8 5 7 10 11 13 3樣例輸出
11解題報(bào)告:
?首先不難證明最終答案的左端點(diǎn)一定取在給定的值處。(這個(gè)可以貪心證明。)
? 然后雙指針掃一遍就完事了。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair using namespace std; const int MAX = 2e5 + 5; ll a[MAX]; int main() {ll n,m,k,ans;cin>>n>>m>>k;for(int i = 1; i<=n; i++) scanf("%lld",a+i);sort(a+1,a+n+1);int l=n,r=n;while(l>=1 && r>=1) {if(a[l] + k - 1 < a[r]) r--;else {if(r - l + 1 >= k - m) {ans = a[l] + k - 1;break;}else l--;}}cout << ans;return 0 ;}雙指為了更清晰的表達(dá)思路(是對(duì)每一個(gè)左指針,右指針進(jìn)行的決策),一般用for循環(huán),可以這么寫(xiě):
代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair using namespace std; const int MAX = 2e5 + 5; ll a[MAX]; int main() {ll n,m,k,ans;cin>>n>>m>>k;for(int i = 1; i<=n; i++) scanf("%lld",a+i);sort(a+1,a+n+1);int l=n,r=n;for(;l > 0;--l){while(a[l] + k - 1 < a[r]) r--;if(r - l + 1 >= k - m){ans = a[l] + k - 1; break;}}cout << ans;return 0 ;}?
總結(jié)
以上是生活随笔為你收集整理的【hihocoder - offer编程练习赛60 B】最大顺子(双指针,思维)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: soundtrax.exe - soun
- 下一篇: 【ZOJ - 3780】Paint th