国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

HDU - 3567 IDA* + 曼哈頓距離 + 康托 [kuangbin帶你飛]專題二

2019-11-08 19:56:42
字體:
供稿:網(wǎng)友

     這題難度頗大啊,TLE一天了,測試數(shù)據(jù)組數(shù)太多了。雙向廣度優(yōu)先搜索不能得到字典序最小的,一直WA。

     思路:利用IDA*算法,當(dāng)前狀態(tài)到達(dá)目標(biāo)狀態(tài)的可能最小步數(shù)就是曼哈頓距離,用于搜索中的剪枝。下次搜索的限制不能直接加1,會(huì)超時(shí),應(yīng)該從當(dāng)前狀態(tài)到目標(biāo)狀態(tài)最小限制開始搜索。

     AC代碼

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<cmath>using namespace std;const int maxn = 4e5 + 5;int vis[maxn];int st[9], goal[9];const int dx[] = {1,0,0,-1};const int dy[] = {0,-1,1,0};const char dir[] = {'d','l','r','u'};int fact[9], loc[9];void deal() {  //1~8階乘打表,方便編碼 	fact[0] = 1;	for(int i = 1; i < 9; ++i) fact[i] = fact[i - 1] * i;}int KT(int *a) {	int code = 0;	for(int i = 0; i < 9; ++i) {		int cnt = 0;		for(int j = i + 1; j < 9; ++j) if(a[j] < a[i]) cnt++;		code += fact[8 - i] * cnt;	}	return code;} void get_pos() {	for(int i = 0; i < 9; ++i) {		loc[goal[i]] = i;	}}int get_h(int *a) { //曼哈頓距離 	int cnt = 0;	for(int i = 0; i < 9; ++i) {		if(a[i] == 0 || i == loc[a[i]]) continue;		int x = i / 3, y = i % 3;		int n = loc[a[i]];		int px = n / 3, py = n % 3;		cnt += abs(x - px) + abs(y - py);	}	return cnt;}char ans[50];int a[9];// step + h <= maxd int maxd, nextd;int dfs(int step, int pos) {	int h = get_h(a); // cut	//PRintf("h = %d/n", h);	if(h == 0) {		printf("%d/n", step);		ans[step] = '/0';		printf("%s", ans);		return 1;	}	if(step + h > maxd) {		nextd = min(nextd, step + h);		return 0;	}	int x = pos / 3, y = pos % 3;	for(int i = 0; i < 4; ++i) {		int px = x + dx[i], py = y + dy[i];		if(px < 0 || py < 0 || px >= 3 || py >= 3) continue;		int pz = px * 3 + py;		swap(a[pos], a[pz]);		int code = KT(a);		if(vis[code]) {			swap(a[pos], a[pz]);			continue;		}		vis[code] = 1;		ans[step] = dir[i];		if(dfs(step + 1, pz)) return 1;		vis[code] = 0;		swap(a[pos], a[pz]);	}	return 0; } int main() {	deal(); 	char str[50];	int T, kase = 1;	scanf("%d", &T);	while(T--) {		int pos;		scanf("%s", str);		for(int i = 0; i < 9; ++i) {			if(str[i] == 'X') {				pos = i;				st[i] = 0;			}			else st[i] = str[i] - '0';		}						scanf("%s", str);		for(int i = 0; i < 9; ++i) {			if(str[i] == 'X') goal[i] = 0;			else goal[i] = str[i] - '0';		}		get_pos();				printf("Case %d: ", kase++);				int code = KT(st);		vis[code] = 1;		for(maxd = get_h(st);;) {			nextd = 1 << 30; 			memcpy(a, st, sizeof(a));			memset(vis, 0, sizeof(vis));			if(dfs(0, pos)) break;			maxd = nextd;		}		printf("/n");	}	return 0;}如有不當(dāng)之處歡迎指出!


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 澄江县| 长武县| 南华县| 长治县| 呼伦贝尔市| 龙井市| 玉溪市| 青州市| 霸州市| 汝南县| 民和| 璧山县| 红桥区| 滦平县| 射洪县| 金塔县| 龙南县| 东丰县| 眉山市| 渭源县| 绥德县| 五台县| 临朐县| 普定县| 敦化市| 东宁县| 洞口县| 崇左市| 双桥区| 睢宁县| 武强县| 岗巴县| 甘洛县| 邮箱| 安塞县| 凤翔县| 新兴县| 东乌| 泽州县| 咸阳市| 温宿县|