hdu1158Employment Planning
我有两个想法,其中一个超时,另外一个不知道怎么表达,结果悲剧地看了答案,可惜正确的答案跟我的想法一样
ACCEPT
#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int N = 10000; const int inf = 0xfffffff; int mon[13]; int dp[13][N]; int main() { //freopen("data.in", "r", stdin); int m, i, j, k; while(scanf("%d", &m), m) { int hire, fire, salary, max, min, cost; memset(dp, 0, sizeof(dp)); memset(mon, 0, sizeof(mon)); scanf("%d%d%d", &hire, &salary, &fire); max = -inf; for(i = 1; i <= m; i++) { scanf("%d", mon + i); max = max > mon[i] ? max : mon[i]; } for(i = mon[1]; i <= max; i++) dp[1][i] = (hire+salary) * i; for(i = 2; i <= m; i++) { for(j = mon[i]; j <= max; j++) { min = inf; for(k = mon[i-1]; k <= max; k++) { if(k <= j) cost = (j-k)*hire + j*salary + dp[i-1][k]; else cost = (k-j)*fire + j*salary + dp[i-1][k]; if(min > cost) min = cost; } //printf("%d\n", min); dp[i][j] = min; } } min = inf; for(i = mon[m]; i <= max; i++) if(min > dp[m][i]) min = dp[m][i]; printf("%d\n", min); } return 0; }
我的代码,搜索,超时了
#include "iostream" #define INF 1000000000 using namespace std; int best=INF,n,hire,salay,fire,i,num[1100]; void dfs(int month,int cost,int much){ cost+=much*salay; if(month==n){ //cout<<"cost "<<cost<<endl; if(best>cost){best=cost;return;} else return; } //cout<<"month "<<month<<" cost "<<cost<<endl; if(much==num[month+1])dfs(month+1,cost,much); else if(much<num[month+1]){cost+=(num[month+1]-much)*hire;much=num[month+1];dfs(month+1,cost,much);} else { int ans=much-num[month+1]; for(int i=0;i<=ans;i++){ dfs(month+1,cost+i*fire,much-i); } } } int main(){ int cost; while(1){ cin>>n; if(!n)break; cin>>hire>>salay>>fire; for(i=1;i<=n;i++)cin>>num[i]; best=INF; cost=num[1]*hire; dfs(1,cost,num[1]); cout<<best<<endl; } }