2.情报传递1【算法赛】 - 蓝桥云课 (lanqiao.cn)
思想
贪心策略
从a到b枚举直到到达目的地b:
- 优先尝试移动2步(检查是否安全)
- 若不安全则尝试移动1步
- 确保不会移动到危险城市
#include<iostream>
#define int long long
using namespace std;
int ans;
void solve()
{
int a, b, c; cin >> a >> b >> c;
for (int i = a; i <= b; i++)
{
int temp = i;
int t = temp;
int t1 = temp + 1;
int t2 = temp + 2;
if (t % c != 0)
{
if (t1 % c != 0 && t2 % c != 0)
{
ans++;
i++;
}
else if (t1 % c != 0)
{
ans++;
i++;
}
else if (t2 % c != 0)
{
ans++;
i++;
}
}
}
cout << ans << endl;
}
signed main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int t; cin >> t;
while (t--)
{
solve();
}
return 0;
}
用while循环更容易控制走x+1还是x+2
#include<iostream>
using namespace std;
void solve() {
int a, b, c;
cin >> a >> b >> c;
int days = 0;
int current = a;
while (current < b) {
// 优先尝试移动2步
if (current + 2 <= b) {
if ((current + 2) % c != 0) {
current += 2;
}
else if ((current + 1) % c != 0) {
current += 1;
}
else {
// 两个选择都危险,必须移动1步到current+1
// 但根据题意保证a,b不是c的倍数,所以不会无限循环
current += 1;
}
}
else {
// 只能移动1步
current += 1;
}
days++;
}
cout << days << endl;
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int t; cin >> t;
while (t--) {
solve();
}
return 0;
}
思想
如果说鲁智深的下一个城市是c的倍数的城市,那么就让他往下走两个城市。如果他的往下第二个城市是c的倍数的城市,那么就让他走到下一个城市。如果说再走一步就走到了终点,那么就再走一步即可,否则如果再走两步才是终点,那么就再走两步。
code
#include<bits/stdc++.h>
#define int long long
using namespace std;
int day;
void solve()
{
int a,b,c;cin>>a>>b>>c;
while(a!=b)
{
if((a+1)%c==0)
{
a+=2;
day++;
}
if((a+2)%c==0)
{
a=a+1;
day++;
}
if(a+1==b)
{
a=a+1;
day++;
}
else
{
a=a+2;
day++;
}
}
cout<<day<<endl;
}
signed main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int t;cin>>t;
while(t--)
{
solve();
}
return 0;
}