【csp模拟赛九】--dfs3
这道题贪心错误:直接dfs就行,枚举新开一个还是往之前的里面塞
贪心代码(80):
#include<cstdio> #include<algorithm> #include<cstdlib> #include<iostream> #define N 10500 using namespace std; int read() { int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){ if(ch=='-')f=-1;ch=getchar(); } while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } int n,W,ans,wei,len1,len2,tot,c[N]; bool vis[N]; struct node{ int val,id; }a[N],b[N]; bool cmp1(const node &a,const node &b) { return a.val>b.val; } bool cmp2(const node &a,const node &b) { return a.val<b.val; } int main() { #ifdef yilnr #else freopen("climb.in","r",stdin); freopen("climb.out","w",stdout); #endif n=read(); wei=read(); for(int i=1;i<=n;i++) { a[i].val=read(); b[i].val=a[i].val; a[i].id=b[i].id=i; } sort(a+1,a+n+1,cmp2); sort(b+1,b+n+1,cmp1); while(tot!=n) { ans++; W=wei; len2=1; while(W>=b[len2].val && len2<=n) { if(!vis[b[len2].id]) { W-=b[len2].val; vis[b[len2].id]=1; tot++; } len2++; } for(int i=1;i<=n;i++)c[i]=a[i].val; len1=upper_bound(c+1 , c+n+1 , W) - c; len1--; while(W>=a[len1].val && len1>=1) { if(!vis[a[len1].id]) { W-=a[len1].val; vis[a[len1].id]=1; tot++; } len1--; } } printf("%d\n",ans); fclose(stdin);fclose(stdout); return 0; } /* 5 1996 1 2 1994 12 29 */
代码:
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; int n,m; int a[50]; int ans,sta[50]; inline void DFS(int opt,int cnt) { if(cnt >= ans) return ; if(opt == n + 1) { ans = min(cnt,ans); return ; } for(int i = 1;i <= cnt;i ++) { if(sta[i] + a[opt] <= m) { sta[i] += a[opt]; DFS(opt + 1,cnt); sta[i] -= a[opt]; } } sta[cnt + 1] = a[opt]; DFS(opt + 1,cnt + 1); sta[cnt + 1] = 0; } int main() { freopen("climb.in","r",stdin); freopen("climb.out","w",stdout); scanf("%d%d",&n,&m); for(int i = 1;i <= n;i ++) scanf("%d",&a[i]); sort(a + 1,a + n + 1,greater<int>()); ans = n; DFS(1,1); printf("%d",ans); fclose(stdin); fclose(stdout); return 0; }