【TLE】10123UVa不要歪(贪心)

来源:互联网 发布:mac软件安装其它盘 编辑:程序博客网 时间:2024/05/17 22:14

一个个放上去与一个个取下来并在判断木板是否平衡时无差别(都会达到相同的状态);

#include<stdio.h>#include<string.h>int bdlen;int bdwt;int numpk;int pos[30];int wt[30];int used[30];int ans[30];bool dfs(int cur, double left, double right){if(cur == numpk){return true;}for(int i = 0; i < numpk; ++i){if(!used[i]){double ll,rr;ll = left + (pos[i] + 1.5)*wt[i];rr = right + (pos[i] - 1.5)*wt[i];if(ll >= 0 && rr <=0){used[i] = 1;ans[cur] = i;if(dfs(cur+1, ll, rr))return true;used[i] = 0;}}}return false;}int main(){freopen("input.txt","r",stdin);freopen("out.txt","w",stdout);int numcase = 1;while(scanf("%d%d%d", &bdlen, &bdwt, &numpk) == 3){if(!bdlen && !bdwt && !numpk)break;for(int i = 0; i < numpk; ++i){scanf("%d%d", &pos[i], &wt[i]);}memset(used, 0, sizeof(used));printf("Case %d:\n", numcase++);if(!dfs(0, 3*bdwt/2, -3*bdwt/2)){printf("Impossible\n");}else{for(int i = numpk-1; i >= 0; --i){printf("%d %d\n", pos[ans[i]], wt[ans[i]]);}}}}


最多有20个箱子,20!高达2*(10^18),超时!


参考http://blog.csdn.net/keshuai19940722/article/details/9768973 思路自己写


#include<stdio.h>#include<string.h>#define LEFT 0#define MID 30#define RIGHT 60int bdlen;int bdwt;int numpk;int pos[90];int wt[90];int ans[30];int lfc[90];int rfc[90]; //其实这里应该用struct的void swap(int* d, int i, int j){int t = d[i];d[i] = d[j];d[j] = t;}void lsorting(int start, int end){for(int i = start+1; i < end; ++i){for(int j = i-1; j >= start && lfc[j] < lfc[j+1]; --j){swap(pos, j, j+1);swap(wt, j, j+1);swap(lfc, j, j+1);swap(rfc, j, j+1);}}}void rsorting(int start, int end){for(int i = start+1; i < end; ++i){for(int j = i-1; j >= start && rfc[j] > rfc[j+1]; --j){swap(pos, j, j+1);swap(wt, j, j+1);swap(lfc, j, j+1);swap(rfc, j, j+1);}}}int main(){freopen("input.txt","r",stdin);//freopen("out.txt","w",stdout);int numcase = 1;while(scanf("%d%d%d", &bdlen, &bdwt, &numpk) == 3){if(!bdlen && !bdwt && !numpk)break;double lfulcrum = 3*bdwt/2;double rfulcrum = -3*bdwt/2;int lcnt, rcnt, mcnt;lcnt = LEFT;mcnt = MID;rcnt = RIGHT;int cur = 0;int p,w;for(int i = 0; i < numpk; ++i){scanf("%d%d", &p, &w);if(p <= 1.5 && p >= -1.5){pos[mcnt] = p;wt[mcnt] = w;ans[cur++] = mcnt++;lfulcrum += (p+1.5)*w;rfulcrum += (p-1.5)*w;}else if(p < -1.5){pos[lcnt] = p;wt[lcnt] = w;lfc[lcnt] = (p+1.5)*w;rfc[lcnt++] = (p-1.5)*w;}else {pos[rcnt] = p;wt[rcnt] = w;lfc[rcnt] = (p+1.5)*w;rfc[rcnt++] = (p-1.5)*w;}}//sorting changes pos wt lfc rfclsorting(LEFT, lcnt);rsorting(RIGHT, rcnt);//int i = LEFT, j = RIGHT;bool contin = true;while(contin && (i < lcnt || j < rcnt)){contin = false;while(i < lcnt && lfulcrum + lfc[i] >= 0){lfulcrum += lfc[i];rfulcrum += rfc[i];ans[cur++] = i++;contin = true;}while(j < rcnt && rfulcrum + rfc[j] <= 0){lfulcrum += lfc[j];rfulcrum += rfc[j];ans[cur++] = j++;contin = true;}}printf("Case %d:\n", numcase++);if(cur != numpk){printf("Impossible\n");}else {for(int g = numpk-1; g >= 0; --g){printf("%d %d\n", pos[ans[g]], wt[ans[g]]);}}}}



原创粉丝点击