雷火盘古笔试题《打怪兽》到底该怎么打才比较快?
想来也被这道题困扰了十多天了。:<
这是我当时的代码,用了BFS的思路(贼傻瓜),只通过了20%的测试用例,时间复杂度太高了。现在也没想出比较好的方法,求一个茅塞顿开啊!
#include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <string> #include <queue> using namespace std; /* Approach: BFS */ struct Node { int HP; int AP; int HM; int AM; }; int main() { int HP = 0, AP = 0, HM = 0, AM = 0, B = 0, D = 0; cin >> HP >> AP >> HM >> AM >> B >> D; Node curr { HP, AP, HM, AM }; queue<Node> Q; int step = 0; Q.push(curr); while (!Q.empty()) { int size = Q.size(); // 出队队列当前所有元素 for (int i = 0; i < size; ++i) { Node curr = Q.front(); Q.pop(); // 若怪兽血量降为0,则获胜,(因为人先攻击,即使这个时候人的血量也降为0,依然是人胜利) if (curr.HM <= 0) { cout << step << endl; return 0; } // 若当前节点HP已经降为0,则此状态失败,到下一个节点 if(curr.HP <= 0) continue; // attack 分支 Node attack { curr.HP - curr.AM, curr.AP, curr.HM - curr.AP, curr.AM }; // recover 分支 Node recover { HP - curr.AM, curr.AP, curr.HM, curr.AM }; // enhance 分支 Node enhance { curr.HP - curr.AM, curr.AP + B, curr.HM, curr.AM }; // weaken 分支 curr.AM = max(0, curr.AM - D); Node weaken { curr.HP - curr.AM, curr.AP, curr.HM, curr.AM }; Q.push(attack); Q.push(recover); Q.push(enhance); Q.push(weaken); } ++step; } cout << "IMPOSSIBLE" << endl; return 0; }#笔试题目##实习#