推公式 AcWing 125. 耍杂技的牛
原题链接
算法标签
贪心
思路
1 按照牛重量与承重量之和从大到小排序
2 从前向后枚举, 记录所有奶牛的风险值中的最大值
证明
即第I头牛重量与承重量之和>第I+1头牛重量与承重量之和时
交互位置
所有奶牛的风险值中的最大值一定会降低
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
struct Risk{
int w, s;
}risk[N];
bool cmp(Risk A, Risk B){
return A.s+A.w<B.s+B.w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n=read();
rep(i, 0, n){
risk[i].w=read(), risk[i].s=read();
}
sort(risk, risk+n, cmp);
int mx=-0x3f3f3f3f;
int sum=0;
rep(i, 0, n){
mx=max(mx, sum-risk[i].s);
sum+=risk[i].w;
}
printf("%lld", mx);
return 0;
}
Time Limit Exceeded代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
struct Risk{
int w, s;
}risk[N];
bool cmp(Risk A, Risk B){
return A.s+A.w<B.s+B.w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n=read();
rep(i, 0, n){
risk[i].w=read(), risk[i].s=read();
}
sort(risk, risk+n, cmp);
int mx=-0x3f3f3f3f;
rep(i, 0, n){
int sum=0;
rep(j, 0, i){
sum+=risk[j].w;
}
mx=max(mx, sum-risk[i].s);
}
printf("%lld", mx);
return 0;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈