http://xcacm.hfut.edu.cn/problem.php?id=1213
set + 搜索
姐姐是用搜索+二分做的,效率要高很多
#include<iostream> #include<cstdio> #include<cstring> #include<set> using namespace std; int x[]={ 0, 0,-1, 1}; int y[]={ 1,-1, 0, 0}; int lable[105][105],d[105][105]; int T,m,n,p,q,deepth=0,cake=0; void dfs(int a,int b) { if(d[a][b]>deepth||a<0||a>=m||b<0||b>=n||lable[a][b]==1){return;} lable[a][b]=1; cake++; for(int i=0;i<4;i++) { if(a+x[i]<0||a+x[i]>=m||b+y[i]<0||b+y[i]>=n){continue;} dfs(a+x[i],b+y[i]); } return; } void solve() { int i,j; for(i=0; i<m; i++) { if(lable[i][0]==1) { continue; } dfs(i,0); } for(i=0; i<m; i++) { if(lable[i][n-1]==1) { continue; } dfs(i,n-1); } for(j=0; j<n; j++) { if(lable[0][j]==1) { continue; } dfs(0,j); } for(j=0; j<n; j++) { if(lable[m-1][j]==1) { continue; } dfs(m-1,j); } } int main() { int i,j; scanf("%d",&T); while(T--) { scanf("%d%d%d%d",&m,&n,&p,&q); set<int>donser; for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&d[i][j]); donser.insert(d[i][j]); } } while(1) { deepth=*donser.begin(); solve(); donser.erase(deepth); if(cake>=p&&cake<=q) { cout<<deepth<<endl; cake=0; memset(lable,0,sizeof(lable)); memset(d,0,sizeof(d)); break; } if(donser.size()==0||cake>q) { cout<<"-1"<<endl; cake=0; memset(lable,0,sizeof(lable)); memset(d,0,sizeof(d)); break; } cake=0; memset(lable,0,sizeof(lable)); } } return 0; }