T1 T638475 调酒大师
我在赛时用了快 才拿了 分 …
赛时代码:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=1e5+10;
ll t,x,y;
int main(){
ios::sync_with_stdio(0);
cin>>t;
while(t--){
cin>>x>>y;
if(x==1||y==1){
cout<<1<<'\n';
continue;
}
if(x==y){
cout<<(x>>1)<<'\n';
continue;
}
ll ans=0,t=(x+y)/4;
if(x>y)swap(x,y);
if(x==y*3){
cout<<y<<'\n';
continue;
}
while(!(abs(x-y)<=1)&&x!=0&&y>0){
x--;
y-=3;
ans++;
}
// cout<<ans<<'\n';
ans+=min(x,y)/2;
cout<<ans<<'\n';
}
return 0;
}这里用的是纯暴力的写法,自然会 TLE 。
那么,正解怎么写呢?
- 可以发现,两份果汁 两份白酒是最均衡的选择,即 。
但是,如果果汁和白酒的数量不一样呢?
- 那就可以用 的方式来调,即 。
再在两者之间选最小值就行啦
正解:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=1e5+10;
ll t,x,y;
int main(){
ios::sync_with_stdio(0);
cin>>t;
while(t--){
cin>>x>>y;
cout<<min((x+y)/4,min(x,y))<<'\n';
}
return 0;
}T2 T638471 小梦的su7
su7不是小米的吗
一道贪心题。
似乎还是加油站问题
因为赛时没写所以就不解释了
因为第 个充电站距离起点仅能为第 块电池充电,所以尽量用接来下要充的电池。
暴力 的时间复杂度是不行的,所以要加点优化。
因为要尽量用接来下要充的电池,过了充电站就可以把站点删掉,所以用 最小堆 是最好的选择。
思路: 不断选择最近可以充电的电池,用完之后,把电池删掉,插入这个电池的下一个充电站位置。
这样的话,时间复杂度仅为 。
代码:
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
#define pii pair<int,int>
#define pos first
#define idx second
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
typedef long long ll;
using namespace std;
const int N = 1e5 + 5;
int a[N], x[N], t[N];
int r[N]; // 每块电池的充电上限
signed main() {
int n, m;
cin >> n >> m;
queue<int> yxj[n + 1]; //每个电瓶用一个队列存储优先级,即充电站位置
priority_queue<pii, vector<pii>, greater<pii>> s;// 按照pair的第一个键值升序排列的最小堆
for (int i = 1; i <= n; i++) {
cin >> a[i];
r[i] = a[i]; // 保存电池容量上限
}
for (int i = 1; i <= m; i++) {
cin >> x[i] >> t[i]; // 保证x从小到大
yxj[t[i]].push(x[i]); // 依次存储第t[i]块电池的充电站位置(依次升序)
}
for (int i = 1; i <= n; i++) {
yxj[i].push(MOD); //给所有电池都设置一个极大位置的充电站
}
for (int i = 1; i <= n; i++) {
int pos = yxj[i].front(); // 第i块电池目前最近的充电站
yxj[i].pop();
s.push({pos, i}); // 将第i块电池最近充电站位置和i打包丢进优先队列。
// 优先队列按位置降序,显然里面应该存储的是每块电池及最近的充电站位置
}
int ans = 0 ;
for (int i = 1; i <= m; i++) {
int len = x[i] - x[i - 1]; //当前充电站与上一站的距离
while (len > 0) { //按照优先队列的顺序用电,优先使用离充电站近的电池
if (s.empty())break;
pii top = s.top();
s.pop();
if (a[top.idx] <= len)
{
len -= a[top.idx];
a[top.idx] = 0;
}
else
{
a[top.idx] -= len;
len = 0;
s.push(top);
break;
}
}
if (len > 0) //如果电量不足以到达充电站
{
ans += (x[i] - x[i - 1] - len);
break;
}
else // 到达第i个充电站,给t[i]电池充满
{
a[t[i]] = r[t[i]]; // 充满
int fi = yxj[t[i]].front(); // 下一个充电站位置
yxj[t[i]].pop();
if(s.top().idx == t[i]) s.pop(); // 先确定堆顶是t[i],再出队
s.push({fi, t[i]}); // 更新
ans += x[i] - x[i - 1];
}
}
for (int i = 1; i <= n; i++) {
ans += a[i]; //如果有剩余电量,增加到ans中
}
cout << ans << endl;
return 0;
}贴: 最小堆 的定义方法为 priority_queue<pii, vector<pii>, greater<pii> > ; ,pii 为 pair<int,int> 。