写在前面

  • 题目很简单
  • 无须测试用例
  • 需要调整逻辑顺序,实测3分钟(解题已算超时)

测试用例

100 4
8 0 100 2
3 1 50 1
5 1 200 6
7 0 200 8

Win 100! Total = 200.
Lose 50. Total = 150.
Not enough tokens. Total = 150.
Not enough tokens. Total = 150.

100 4
8 0 100 2
3 1 200 1
5 1 200 6
7 0 200 8

Win 100! Total = 200.
Lose 200. Total = 0.
Game Over.

ac代码(未优化)

  • 代码部分冗余
#include <iostream>
using namespace std;
int main()
{
int total, k;
scanf("%d %d", &total, &k);
int n1, b1, t1, n2;
for(int i=0; i<k; i++)
{
if(total == 0)
{
printf("Game Over.");
break;
}
scanf("%d %d %d %d",&n1,&b1,&t1,&n2);
if(b1==0)
{
if(total<t1)
printf("Not enough tokens. Total = %d.\n", total);
else
{
if(n1>n2)
{
total += t1;
printf("Win %d! Total = %d.\n", t1, total);
}
else
{
if(total>=t1)
{
total -= t1;
printf("Lose %d. Total = %d.\n", t1, total);
}
}
}
}
if(b1==1)
{
if(total<t1)
printf("Not enough tokens. Total = %d.\n", total);
else
{
if(n1<n2)
{
total += t1;
printf("Win %d! Total = %d.\n", t1, total);
} else {
if(total>=t1)
{
total -= t1;
printf("Lose %d. Total = %d.\n", t1, total);
}
}
}
}
}
return 0;
}

ac代码(优化后)

  • 数值交换
  • 去除重复代码
#include <iostream>
using namespace std;
int main()
{
int total, k;
scanf("%d %d", &total, &k);
int n1, b1, t1, n2;
for(int i=0; i<k; i++)
{
if(total == 0)
{
printf("Game Over.");
break;
}
scanf("%d %d %d %d",&n1,&b1,&t1,&n2);
if(b1==1)
{
n1 = n1 ^ n2;
n2 = n1 ^ n2;
n1 = n1 ^ n2;
}
if(total<t1)
printf("Not enough tokens. Total = %d.\n", total);
else
{
if(n1>n2)
{
total += t1;
printf("Win %d! Total = %d.\n", t1, total);
}
else
{
total -= t1;
printf("Lose %d. Total = %d.\n", t1, total);
}
}
}
return 0;
}

参考代码

#include <iostream>
using namespace std;
int main() {
int T, K, n1, n2, b, t;
scanf("%d %d", &T, &K);
for (int i = 0; i < K; i++) {
scanf("%d %d %d %d", &n1, &b, &t, &n2);
int ans = n1 > n2 ? 0 : 1;
if (T == 0) {
printf("Game Over.\n");
return 0;
} else if (t > T) {
printf("Not enough tokens. Total = %d.\n", T);
} else if (ans == b) {
T += t;
printf("Win %d! Total = %d.\n", t, T);
} else if (ans != b) {
T -= t;
printf("Lose %d. Total = %d.\n", t, T);
}
}
return 0;
}