165. 小猫爬山 - AcWing题库(dfs)
cpp
#include<iostream>
#include<string>
#include<bitset>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=18;
bool vis[N];
int a[N],n,ans,sum[N],k;
bool cmp(int x,int y){
return x>y;
}
void dfs(int x,int t){
if(t>=ans)return;
if(x==n){
ans=min(ans,t);
return;
}
for(int i=1;i<=t;i++){//第一种选择--放到原数组
if(sum[i]+a[x]<=k){
sum[i]+=a[x];
dfs(x+1,t);
sum[i]-=a[x];
}
}
sum[t+1]=a[x];//第二种选择放到新数组中
dfs(x+1,t+1);
sum[t+1]=0;
}
int main(){
cin>>n>>k;
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n,cmp);
ans=n;
dfs(0,1);
cout<<ans<<endl;
}
167. 木棒 - AcWing题库(dfs+剪枝--重点理解)
cpp
#include<iostream>
#include<string>
#include<bitset>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
int a[65];
int length,sum;
bool vis[65];
bool cmp(int x,int y){
return x>y;
}
int dfs(int u,int h,int x){//u为几组木棍成功, h目前长度 ,x为枚举位置
if(u*length==sum)return 1;//总长度相等就成功
if(h==length)return dfs(u+1,0,0);//这组成功
for(int i=x;i<n;i++){
if(h+a[i]>length||vis[i])continue;
vis[i]=true;//标记使用
if(dfs(u,h+a[i],i+1)==1)return 1;
vis[i]=false;//取消标记
if(!h||a[i]+h==length)return false;//第一根失败,或最后一根失败直接失败
int j=i;//长度相等的一定失败
while(j<n&&a[j]==a[i])j++;
i=j-1;
}
return false;
}
int main(){
while(cin>>n&&n){
memset(vis,0,sizeof(vis));
sum=0;
for(int i=0;i<n;i++){
cin>>a[i];
sum+=a[i];
}
sort(a,a+n,cmp);
length=1;
for(length=1;length<=sum;length++){
if(sum%length==0&&dfs(0,0,0)){
cout<<length<<endl;
break;
}
}
}
}
cpp
#include<iostream>
#include<queue>
#include<map>
using namespace std;
map<int,int>ma;
typedef pair<int,int>PII;
int a[1000005];
int p[1000005];
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
ma[a[0]]++;
int s=1;
int ans=0;
for(int i=0,j=0;j<n;){
if(s<=2){
ans=max(ans,j-i+1);
j++;
if(ma[a[j]]==0)s++;
ma[a[j]]++;
}
else {
ma[a[i]]--;
if(ma[a[i]]==0)s--;
i++;
}
}
cout<<ans<<endl;
}
3321. ATM队列 - AcWing题库(排序--签到)
cpp
#include<iostream>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
map<int,int>ma;
typedef pair<int,int>PII;
struct node{
int x,y;
}a[1000005];
bool cmp(node q,node w){
if(q.x!=w.x)return q.x<w.x;
return q.y<w.y;
}
int main(){
int t;
cin>>t;
for(int i=1;i<=t;i++){
int n,k;
cin>>n>>k;
for(int j=0;j<n;j++){
int q;
cin>>q;
a[j].x=q/k;
if(q%k!=0)a[j].x++;
a[j].y=j+1;
}
printf("Case #%d: ",i);
sort(a,a+n,cmp);
for(int j=0;j<n;j++){
cout<<a[j].y<<' ';
}
cout<<endl;
}
}