比較簡單, 搜索全部情況! 代碼如下: #include <algorithm> #include <string> #include <vector> using namespace std; /************** Program Begin *********************/ class PipeCuts { public: double probability(vector <int> weldLocations, int L) { double res; int all = 0; int good = 0; int front, below; for (int i = 0; i < weldLocations.size() - 1; i++) { for (int j = i + 1; j < weldLocations.size(); j++) { ++all; front = max(weldLocations[i], weldLocations[j]); below = min(weldLocations[i], weldLocations[j]); if ( front - below > L || below > L || 100 - front > L) { ++good; } } } res = (double) good / all; return res; } }; /************** Program End ************************/ #include <algorithm> #include <string> #include <vector> using namespace std; /************** Program Begin *********************/ class PipeCuts { public: double probability(vector <int> weldLocations, int L) { double res; int all = 0; int good = 0; int front, below; for (int i = 0; i < weldLocations.size() - 1; i++) { for (int j = i + 1; j < weldLocations.size(); j++) { ++all; front = max(weldLocations[i], weldLocations[j]); below = min(weldLocations[i], weldLocations[j]); if ( front - below > L || below > L || 100 - front > L) { ++good; } } } res = (double) good / all; return res; } }; /************** Program End ************************/