PAT T1021 Safe Fruit
暴力搜索加剪枝~
看的人好多...更新一下:
这道题的正解应该是求最大团之类的...暴力搜索是拿不到分的,我用了好几种奇怪的技巧用爆搜卡掉了。。。
#include<bits/stdc++.h> using namespace std; const int maxn=1014; const int inf=1e9; int g[maxn][maxn]; int c[maxn]; int N,M; int mincost=1e9; int cost=0; int flag; int tle=0; int ans=0; bool visit[maxn]; vector<int> path,tmp; void dfs (int v,int direction) { tle++; if (tle>1e5) return; if (tmp.size()>path.size()) { path=tmp; mincost=cost; } else if (tmp.size()==path.size()&&cost<mincost) { path=tmp; mincost=cost; } if (direction==1) { v++; while (v<=1000) { flag=0; if (c[v]==0) { v++; continue; } for (int j=0;j<tmp.size();j++) if (g[v][tmp[j]]==1) { flag++; break; } if (flag==0) { tmp.push_back(v); visit[v]=true; cost+=c[v]; dfs (v,1); tmp.pop_back(); visit[v]=false; cost-=c[v]; } v++; } } else { v--; while (v>=0) { flag=0; if (c[v]==0) { v--; continue; } for (int j=0;j<tmp.size();j++) if (g[v][tmp[j]]==1) { flag++; break; } if (flag==0) { tmp.push_back(v); visit[v]=true; cost+=c[v]; dfs (v,0); tmp.pop_back(); visit[v]=false; cost-=c[v]; } v--; } } } int main () { scanf ("%d %d",&M,&N); int u,v; for (int i=0;i<M;i++) scanf ("%d %d",&u,&v),g[u][v]=g[v][u]=1; for (int i=1;i<=N;i++) { scanf ("%d %d",&u,&v); c[u]=v; if (v>999) ans++; } if (ans!=0) dfs (0,1); else dfs (1000,0); printf ("%d\n",path.size()); sort (path.begin(),path.end()); for (int i=0;i<path.size();i++) { if (i!=0) printf (" "); printf ("%03d",path[i]); } printf ("\n%d",mincost); return 0; }