贪心方法就是将所有带宽排序离散化,从小到大枚举以min_band搜索, 在每台设备中寻找带宽大于min_band且价格最小的设备加入计算,到最后若算出的比值比max_t大则更新比值,实际做法我是用DFS将贪心当做剪枝条件。 #include <iostream> #include <vector> #include <algorithm> using namespace std; int tag[105],bandwidth[105][105],price[105][105]; int T,n; double max_t; vector<int> vec; void DFS(int pos,int sum_price,int min_band){ if(pos==n){ //找到最后,更新比值 if( ( (double)min_band / (double)sum_price ) > max_t ) max_t = (double)min_band / (double)sum_price; return ; } int t_price=999999; for(int i=0;i<tag[pos];++i) //搜索满足该最小带宽的设备的最小价格 { if(bandwidth[pos][i]>=min_band && price[pos][i] < t_price ) { t_price=price[pos][i]; } } DFS(pos+1,sum_price+t_price,min_band); } int main(){ int sz; scanf("%d",&T); while(T--){ max_t=0.0; scanf("%d",&n); for(int i=0;i<n;++i){ scanf("%d",tag+i); for(int j=0;j<tag[i];++j){ scanf("%d%d",&(bandwidth[i][j]) , &(price[i][j]) ); vec.push_back( bandwidth[i][j] ); //将所有带宽取值存储 } } sort(vec.begin(),vec.end()); //排序,用vec可以将带宽离散化,不用逐一自增搜索 sz=vec.size(); for(int i=0;i<sz;++i){ if(i>0 && vec[i]==vec[i-1]) continue; //前面已搜索过的重复的值不必再次计算 else DFS(0,0,vec[i]); } printf("%.3lf/n",max_t); } return 0; }