标签:des style blog class code java tar javascript color int string
看到这么一个题,每个人都有一个念头,就是dfs,我也是,于是就写了一个dfs
#include<map> #include<set> #include<queue> #include<cmath> #include<vector> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define inf 0x0f0f0f0f using namespace std; const double pi=acos(-1.0); const double eps=1e-8; typedef pair<int,int>pii; struct node { char name[101]; int deadline; int needtime; }homework[15]; bool vis[16]; int path[16],p[16]; int reduce,n; void dfs(int num,int nowreduce,int nowtime) { if (num==n) { if (reduce>nowreduce) { reduce=nowreduce; for (int i=1;i<=n;i++) p[i]=path[i]; } return; } if (nowreduce>=reduce) return; for (int i=1;i<=n;i++) if (!vis[i]) { vis[i]=true; path[num+1]=i; int temp=nowreduce+nowtime+homework[i].needtime-homework[i].deadline; if (nowtime+homework[i].needtime<homework[i].deadline)temp=nowreduce; dfs(num+1,temp,nowtime+homework[i].needtime); vis[i]=false; } } int main() { //freopen("in.txt","r",stdin); int t; scanf("%d", &t); while (t--) { scanf("%d", &n); for (int i=1;i<=n;i++) { scanf("%s %d %d",&homework[i].name, &homework[i].deadline, &homework[i].needtime); } reduce=inf; memset(vis,0,sizeof(vis)); dfs(0,0,0); printf("%d\n",reduce); for (int i=1;i<=n;i++) printf("%s\n",homework[p[i]].name); } //fclose(stdin); return 0; }
还很高兴自己写了那么一个好的dfs ,谁知一提交,tle了,正常,回头算一下,最坏的情况下为15!,肯定超时,再看n==15;知道肯定是集合上的dp,但是不知道怎么保存路径,和怎么转移方程,于是看了看别人的代码,模仿着写了这个,正所谓一次不会我学,两次不会我还学,我就不相信我会永远不会
#include<map> #include<set> #include<queue> #include<cmath> #include<stack> #include<vector> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define inf 0x0f0f0f0f using namespace std; const double pi=acos(-1.0); const double eps=1e-8; typedef pair<int,int>pii; struct Home { char name[101]; int deadline,needtime; }homework[16]; struct node { int pre,score,time,last; }dp[1<<16]; int main() { //freopen("in.txt","r",stdin); int t,reduce,past,recent,n; scanf("%d", &t); while (t--) { scanf("%d",&n); for (int i=0;i<n;i++) scanf("%s%d%d",homework[i].name, &homework[i].deadline, &homework[i].needtime); int maxstate=1<<n; for (int s=1;s<maxstate;s++) { dp[s].score=inf; for (int i=n-1;i>=0;i--) { recent=1<<i; if (s & recent) { past=s-recent; reduce=dp[past].time+homework[i].needtime-homework[i].deadline; if (reduce<0) reduce=0; if (dp[s].score>dp[past].score+reduce) { dp[s].pre=i; dp[s].last=past; dp[s].time=dp[past].time+homework[i].needtime; dp[s].score=dp[past].score+reduce; } } } } stack<int>path; recent=maxstate-1; while (recent) { path.push(dp[recent].pre); recent=dp[recent].last; } printf("%d\n",dp[maxstate-1].score); while (!path.empty()) { int top=path.top(); printf("%s\n",homework[top].name); path.pop(); } } //fclose(stdin); return 0; }
hdu 1074 Doing Homework,码迷,mamicode.com
标签:des style blog class code java tar javascript color int string
原文地址:http://www.cnblogs.com/chensunrise/p/3702668.html