A1065. A+B and C (64bit)
Given three integers A, B and C in [−2^ 63,2^63], you are supposed to tell whether A+B>C.
Input Specification:
The first line of the input gives the positive number of test cases, T (≤10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.
Output Specification:
For each test case, output in one line Case #X: true if A+B>C, or Case #X: false otherwise, where X is the case number (starting from 1).
Sample Input:
3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0
Sample Output:
Case #1: false
Case #2: true
Case #3: false
该题没有涉及数据结构和算法,只是简单模拟,做题过程中没有考虑到溢出问题,A和B的范围都在[−2^ 63,2^63],所以A+B会有可能超出long long的范围,所以一定要考虑到溢出。
若A>0,B>0时,A+B<0,说明正溢出,A+B一定大于C,为true;
若A<0,B<0时,A+B>0,说明负溢出,A+B一定小于C,为false;
代码:
#include <cstdio>
int main(){
int t;
scanf("%d",&t);
for(int i =1;i<=t;i++){
long long a,b,c,ans;
scanf("%lld%lld%lld",&a,&b,&c);
ans = a+b;
if(a>0&&b>0&&ans<0){
printf("Case #%d: true\n",i);
}
else if(a<0&&b<0&&ans>=0){
printf("Case #%d: false\n",i);
}
else if(ans>c) printf("Case #%d: true\n",i);
else printf("Case #%d: false\n",i);
}
return 0;
}
**
B1020 月饼
月饼是中国人在中秋佳节时吃的一种传统食品,不同地区有许多不同风味的月饼。现给定所有种类月饼的库存量、总售价、以及市场的最大需求量,请你计算可以获得的最大收益是多少。
注意:销售时允许取出一部分库存。样例给出的情形是这样的:假如我们有 3 种月饼,其库存量分别为 18、15、10 万吨,总售价分别为 75、72、45 亿元。如果市场的最大需求量只有 20 万吨,那么我们最大收益策略应该是卖出全部 15 万吨第 2 种月饼、以及 5 万吨第 3 种月饼,获得 72 + 45/2 = 94.5(亿元)。
输入格式:
每个输入包含一个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N 表示月饼的种类数、以及不超过 500(以万吨为单位)的正整数 D 表示市场最大需求量。随后一行给出 N 个正数表示每种月饼的库存量(以万吨为单位);最后一行给出 N 个正数表示每种月饼的总售价(以亿元为单位)。数字间以空格分隔。
输出格式:
对每组测试用例,在一行中输出最大收益,以亿元为单位并精确到小数点后 2 位。
输入样例:
3 20
18 15 10
75 72 45
输出样例:
94.50
代码长度限制
16 KB
时间限制
150 ms
内存限制
64 MB
笔记:虽然出现double类型变量需要考虑除法的方便,可以尽可能将其余变量存储为double,但是一定为int 的还是存为int比较好,否则会出现类型不匹配的连带错误,比如sort函数中就没办法处理double类型变量,还有可能出现答案错误。以及,类似品种信息表,记得struct。
#include <cstdio>
#include <algorithm>
using namespace std;
struct mooncake{
double store;
double sell;
double price;
}cake[1010];
bool cmp(mooncake a,mooncake b)
{
return a.price>b.price;
}
int main ()
{
int N;//要定义为整数,否则sort函数会报错类型
double D;
scanf("%d %lf",&N,&D);
for(int i=0;i<N;i++)
{
scanf("%lf",&cake[i].store);
}
for(int i=0;i<N;i++)
{
scanf("%lf",&cake[i].sell);
cake[i].price=cake[i].sell/cake[i].store;
}
sort(cake,cake+N,cmp);
double ans=0;
for(int i=0;i<N;i++)
{
if(D<=cake[i].store){
ans=ans+cake[i].price*D;
break;
}else{
ans=ans+cake[i].price*cake[i].store;
D=D-cake[i].store;
}
}
printf("%.2f\n",ans);
return 0;
}
"寻找有序序列第一个满足某条件的元素的位置"二分查找模板
int solve(int left,int right)
{
int mid;
while(left<right)//对闭区间[left,right]而言,left==right意味着找到唯一的解
{
mid=(left+right)/2;//取中点
if(条件满足){
right=mid;//往子区间[left.mid]寻找
}else{
left=mid+1;//往子区间[mid+1,right]寻找
}
}
return left;//返回夹出来的范围
}