第三題:
有n個人參加編程比賽,比賽結束後每個人都得到一個分數,現在所有人排成一圈(第一個和第n個相鄰)領取獎品,要求:
1.現在某個人的分數比左右的人告,那麼獎品數量也比左右的人多;
2.每個人至少得到一個獎品
問最少應該準備多少個獎品?
測試用例:
N組數據
每組數組輸入n個人,n個人的分數
輸入:
2
2
1 2
4
1 2 3 3
輸出
3
8
leetcode相似題:candy
思路:先從左至右遍歷,如果i+1的元素比i要大,那個i+1的獎品數就等於i的獎品數+1,否則就保持爲1.然後再從右向左遍歷,如果當前i的分數比i+1的分數要大,那麼當前分數就等於max(當前的分數, i+1的分數+1)。
代碼:
int main()
{
int N;
cin>>N;
while(N--)
{
int n;
int *rates=new int[n];
cin>>n;
for(int i=0;i<n;i++)
cin>>rates[i];
vector<int> num(n, 1); //初始化爲1
for(int i=1;i<n;i++)
{
if(rates[i]>rates[i-1])
num[i]=num[i-1]+1;
}
for(int i=n-1; i>=0; i--)
{
if(rates[i]>rates[(i+1)%n])
num[i]=max(num[i], num[(i+1)%n]+1);
}
int sum=0;
for(int i=0;i<n; i++)
sum+=num[i];
cout<<sum<<endl;
}
return 0;
}
第四題:
有N根繩子,第i根繩子長度爲Li,現在需要M根等長的繩子,你可以對n根繩子進行任意剪裁(不能拼接),請你幫忙設計出這m根繩子最長的長度是多少?
輸入描述:
輸入N,M
N個Li
輸入:
3 4
3 5 4
輸出:
2.50
二分(注意精度,以及保留兩位小數)
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string.h>
#include <algorithm>
using namespace std;
vector<double> L;
int n,m;
bool check(double k)
{
int count=0;
for(int i=0; i<n; i++)
{
count+=L[i]/k;
}
return count>=m;
}
double slove(vector<double>& L)
{
double l=0.f, r=L[n-1]+1.f;
while(l<r)
{
double k=(l+r)/2.0;
if(check(k))
{
l=k;
}
else
{
r=k-0.001;
}
}
return l;
}
int main()
{
cin>>n>>m;
double x;
for(int i=0; i<n; i++)
{
cin>>x;
L.push_back(x);
}
sort(L.begin(), L.end());
double result;
result=slove(L);
printf("%.2f", result);
return 0;
}
第二題:
修正拼寫錯誤:
- 3個相同的字母連在一起,去掉一個:helllo–>hello
- 兩對一樣的字母(AABB型)連在一起,一定是拼寫錯誤,去掉第二對的一個字母就好了,比如:helloo–>hello
- 上面的規則優先“從左到右”匹配,即AABBCC,優先考慮修復AABB,結果爲AABCC
思路:新建一個新的字符串,在新的字符串上進行判斷,如果沒有錯誤就將字符添加到newstring中,否則繼續根據newstring之前的字符串進行判斷。
輸入:
2
helloo
wooooooow
輸出:
hello
woow
代碼:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string.h>
using namespace std;
int main()
{
int N;
cin>>N;
while(N--)
{
string s;
cin>>s;
if(s.size()<2)
{
cout<<s<<endl;
return 0;
}
string newstring=s.substr(0,2);
int i=2,j=2;
while(i<s.size())
{
if(newstring[j-2]==newstring[j-1] && newstring[j-1]==s[i])
{
i++;
}
else if(j>2 &&newstring[j-3]==newstring[j-2] && newstring[j-1]==s[i])
{
i++;
}
else
{
newstring+=s[i];
j++;
i++;
}
}
cout<<newstring<<endl;
}
return 0;
}