UVa658 這不是bug,而是特性

題目:VJ : UVa658

代碼實現:

#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<string>
#include<functional>
using namespace std;
struct Node{
	int cost;
	int id;
	bool operator>(const Node& n)const{
		return this->cost > n.cost;
	}
}; 

int GetNext(int id,string prev,string post)
{
	int mask = 1;
	for(auto iter = prev.rbegin(); iter!=prev.rend(); ++iter){
		if(*iter == '-' && !(id & mask))	//被WA了無數次 
			return -1;
		if(*iter == '+' && (id & mask))		//位操作的慘痛教訓 
			return -1;
		mask <<= 1;
	}
	
	mask = 1;
	for(auto iter = post.rbegin(); iter!=post.rend(); ++iter){
		if(*iter == '-'){
			id = id|mask;
		}
		if(*iter == '+'){
			id = id&(~mask);
		}
		mask <<= 1;
	}
	return id;
}

int main()
{
	int n,m;	//n-bugs數  m-patches數 
	int pid = 0;	//產品編號 
	while(scanf("%d%d",&n,&m)==2 && n){
		++pid;
		vector<int> tm(m);
		vector<string> prev(m);
		vector<string> post(m);
		//將m組patch輸入
		for(int i = 0; i < m; ++i){
			cin >> tm[i] >> prev[i] >> post[i];
		}

		//dijkstra算法 
		vector<bool> visited(1<<n,0);
		int aim = (1<<n)-1;
		priority_queue<Node,vector<Node>,greater<Node> > pq;
		pq.push(Node{0,0});
		bool flag = false;
		while(!pq.empty()){
			Node tn = pq.top();	pq.pop();
			if(visited[tn.id])
				continue;
			visited[tn.id] = true;
			if(tn.id == aim){
				printf("Product %d\n",pid);
				printf("Fastest sequence takes %d seconds.\n\n",tn.cost);
				flag = true;
				break;
			}
			for(int i = 0; i < m; ++i){
				int nextid = GetNext(tn.id,prev[i],post[i]);
				if(nextid != -1 && !visited[nextid]){
					pq.push(Node{tm[i]+tn.cost,nextid});
				}
			}
		} 
		if(!flag){
			printf("Product %d\n",pid);
			printf("Bugs cannot be fixed.\n\n");
		}
	}
	return 0;
}

總結:採用dijkstra算法求最短路徑。被這道題卡了一天半,用的測試數據從題目給出的,到uDebug,再到自己寫程序隨機生成,無論怎麼測都沒問題,但一直WA;打開劉老師的代碼看,發現思路和我寫的相差無幾,代碼各個部分都能對上,然後通過代碼一段一段互換測試,定位出BUG在GetNext()函數,在第一個for循環中位操作後判斷出問題:原代碼爲(id & mask)==1,事實上需(id & mask)>0,因寫代碼時一直想着該位爲1,而該位若不在最低位,結果需>0纔可說明該位爲1。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章