二分求最大满足条件的quality
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <map> using namespace std; typedef long long LL; const int maxn = 1010; int id,n,m,b; map<string,int> vis; int ID(char* str){ string s(str); if(vis.count(s)) return vis[s]; return vis[s] = id++; } struct node{ int price,quality; node(int x=0,int y=0):price(x),quality(y){} }; vector<node> a[maxn]; char str[maxn],src[maxn]; void init(){ for(int i=0;i<id;i++) a[i].clear(); id = 0; vis.clear(); } bool judge(int x){ int all = b; for(int i=0;i<id;i++){ bool ok=false; int min_; for(int j=0;j<a[i].size();j++){ if(a[i][j].quality>=x&&all>=a[i][j].price){ if(!ok){ ok=true; min_=a[i][j].price; } else min_=min(min_,a[i][j].price); } } if(!ok) return false; all-=min_; } return true; } int main() { int T; scanf("%d",&T); while(T--){ init(); scanf("%d %d",&n,&b); for(int i=1;i<=n;i++){ int x,y; scanf("%s %s %d %d",str,src,&x,&y); a[ID(str)].push_back(node(x,y)); } int x=0,y=1e9+1; while(x<y){ int m; m = x+(y-x)/2; if(!judge(m)) y=m; else x=m+1; } printf("%d\n",x-1); } return 0; }
下面是二分函数的另外一种写法;
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <map> using namespace std; typedef long long LL; const int maxn = 1010; int id,n,m,b; map<string,int> vis; int ID(char* str){ string s(str); if(vis.count(s)) return vis[s]; return vis[s] = id++; } struct node{ int price,quality; node(int x=0,int y=0):price(x),quality(y){} }; vector<node> a[maxn]; char str[maxn],src[maxn]; void init(){ for(int i=0;i<id;i++) a[i].clear(); id = 0; vis.clear(); } bool judge(int x){ int all = b; for(int i=0;i<id;i++){ bool ok=false; int min_; for(int j=0;j<a[i].size();j++){ if(a[i][j].quality>=x&&all>=a[i][j].price){ if(!ok){ ok=true; min_=a[i][j].price; } else min_=min(min_,a[i][j].price); } } if(!ok) return false; all-=min_; } return true; } int main() { int T; scanf("%d",&T); while(T--){ init(); scanf("%d %d",&n,&b); for(int i=1;i<=n;i++){ int x,y; scanf("%s %s %d %d",str,src,&x,&y); a[ID(str)].push_back(node(x,y)); } int x=0,y=1e9; //x,y的初始值保证包含所有quality的取值即可,不必故意放大,因为无论左右边第一开始哪一方已经满足条件那么另一方就会向他趋近,直到相等; while(x<y){ int m; m = x+(y-x+1)/2; //m的取值只是为了防止x=y-1时出现死循环; if(!judge(m)) y=m-1; else x=m; } printf("%d\n",x); } return 0; }