T640711 快递费用
简化题意
给定重量 和区域编号 ,费用为 (其中 为区域附加单价)。
思路
1.模拟
- 计算基本费用 。
- 如果重量超过 ,则需要计算超出部分的费用。
- 根据区域编号 ,确定每个区域的附加单价 。
- 计算总费用并输出。
2.复杂度分析
- 时间复杂度:。
- 空间复杂度:。
代码实现
#include<bits/stdc++.h>
using namespace std;
int w,n;
int main(){
cin>>w>>n;
if(w<=500){
cout<<20;
return 0;
}
w-=500;
int cnt=w/500,sum=20;
if(w%500!=0){
cnt++;
}
if(n==1) sum+=cnt*4;
else if(n==2) sum+=cnt*6;
else if(n==3) sum+=cnt*9;
else if(n==4) sum+=cnt*10;
else if(n==5) sum+=cnt*17;
cout<<sum;
return 0;
}T638889 石头布没有剪刀
简化题意
给定一个只含 g 和 p 的字符串 ,表示对手的出拳(石头=g,布=p)。你依次与对手对战,每一位你可出石头或布,规则是:胜=+1,平=0,负=-1。要求在任意前缀内你出的石头数 ≥ 布数的条件下,使得总得分最大,并输出该最大分数。
思路
1. 贪心
- 在保证任意前缀内石头数不少于布数的条件下,优先选择布以最大化总得分。
2. 复杂度分析
- 时间复杂度:,其中 是字符串 的长度。
- 空间复杂度:。
代码实现
#include<bits/stdc++.h>
using namespace std;
string s;
int main(){
cin>>s;
int x=0,y=0,cnt=0;
for(int i=0;i<s.size();i++){
if(y+1<=x){
if(s[i]=='g'){
cnt++;
}
y++;
}
else{
if(s[i]=='p'){
cnt--;
}
x++;
}
}
cout<<cnt;
return 0;
}P2895 [USACO08FEB] Meteor Shower S
简化题意
从起点 出发,在流星按时刻禁用格子的约束下,用最短步数到达一个永不被禁用的格子,若无则输出 。
思路
1.模拟(BFS)
- 使用广度优先搜索(BFS)从起点开始探索所有可达的格子。
- 在每一步中,检查当前格子是否被禁用,如果被禁用,则记录禁用时间。
- 如果到达一个永不被禁用的格子,则输出当前步数并结束搜索。
- 如果搜索完所有可能的路径仍未找到合适的格子,则输出 。
2.复杂度分析
- 时间复杂度:,其中 是格子的数量。
- 空间复杂度:。
代码实现
#include<bits/stdc++.h>
using namespace std;
int m,vis[310][310],dis[310][310];
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
struct node{
int x,y;
};
void bfs(){
queue<node> q;
q.push({0,0});
dis[0][0]=0;
while(q.size()){
node f=q.front();
int x=f.x,y=f.y;
q.pop();
for(int i=0;i<4;i++){
int xx=x+dx[i],yy=y+dy[i];
if(xx>=0&&yy>=0&&(vis[xx][yy]==-1||(vis[xx][yy]!=-2&&vis[xx][yy]<dis[x][y]))){
vis[xx][yy]=-2;
dis[xx][yy]=dis[f.x][f.y]+1;
q.push({xx,yy});
}
}
if(vis[f.x][f.y]==-2){
cout<<dis[x][y];
exit(0);
}
}
cout<<-1;
return;
}
int main(){
for(int i=0;i<310;i++){
for(int j=0;j<310;j++){
vis[i][j]=-1;
}
}
cin>>m;
while(m--){
int x,y,t;
cin>>x>>y>>t;
vis[x][y]=t;
for(int i=0;i<4;i++){
int xx=x+dx[i],yy=y+dy[i];
if(xx>=0&&yy>=0){
if(vis[xx][yy]!=-1){
vis[xx][yy]=min(vis[xx][yy],t);
}
else{
vis[xx][yy]=t;
}
}
}
}
if(vis[0][0]==0){
cout<<-1;
return 0;
}
bfs();
return 0;
}