清華OJ旅行商(TSP)

題目

旅行商(TSP)

Description
Shrek is a postman working in the mountain, whose routine work is sending mail to n villages. Unfortunately, road between villages is out of repair for long time, such that some road is one-way road. There are even some villages that can’t be reached from any other village. In such a case, we only hope as many villages can receive mails as possible.
Shrek hopes to choose a village A as starting point (He will be air-dropped to this location), then pass by as many villages as possible. Finally, Shrek will arrived at village B. In the travelling process, each villages is only passed by once. You should help Shrek to design the travel route.
Input
There are 2 integers, n and m, in first line. Stand for number of village and number of road respectively.
In the following m line, m road is given by identity of villages on two terminals. From v1 to v2. The identity of village is in range [1, n].
Output
Output maximum number of villages Shrek can pass by.
Example
Input
4 3
1 4
2 4
4 3
Output
3
Restrictions
1 <= n <= 1,000,000
0 <= m <= 1,000,000
These is no loop road in the input.
Time: 2 sec
Memory: 256 MB
Hints
Topological sorting
描述
Shrek是一個大山裏的郵遞員,每天負責給所在地區的n個村莊派發信件。但杯具的是,由於道路狹窄,年久失修,村莊間的道路都只能單向通過,甚至有些村莊無法從任意一個村莊到達。這樣我們只能希望儘可能多的村莊可以收到投遞的信件。
Shrek希望知道如何選定一個村莊A作爲起點(我們將他空投到該村莊),依次經過儘可能多的村莊,路途中的每個村莊都經過僅一次,最終到達終點村莊B,完成整個送信過程。這個任務交給你來完成。
輸入
第一行包括兩個整數n,m,分別表示村莊的個數以及可以通行的道路的數目。
以下共m行,每行用兩個整數v1和v2表示一條道路,兩個整數分別爲道路連接的村莊號,道路的方向爲從v1至v2,n個村莊編號爲[1, n]。
輸出
輸出一個數字,表示符合條件的最長道路經過的村莊數。
樣例
見英文題面
限制
1 ≤ n ≤ 1,000,000
0 ≤ m ≤ 1,000,000
輸入保證道路之間沒有形成環
時間:2 sec
空間:256 MB
參考:參考

我的代碼:

#include<cstdio>
#define MAXSIZE 1000000
#define GetMax(a,b) a>b?a:b
//注意全局變量數組的元素都會自動初始化爲0

using namespace std;
struct ENode{
	int vsub;
	ENode *succ;
};

struct VNode{
	int in,len;//相對於鄰接表結構,額外添加了屬性len以計算到每個頂點的最大路徑
	ENode *fstEdge;
};

VNode adjList[MAXSIZE];ENode *t;
int visited[MAXSIZE],stack[MAXSIZE],top=0,maxlen=0,n,e,i,j;
void TSort(){
	for(int k=0;k<n;k++)if(!adjList[k].in)stack[++top]=k;
	while(top){
		int v=stack[top--];
		for(ENode *p=adjList[v].fstEdge;p;p=p->succ){
//策略:動態規劃-不斷的更新到每個入度爲0的頂點的鄰居的最大路徑長度
//相對於拓撲排序,額外添加了下述2句以更新到每個鄰居的最大路徑長度和記錄圖的最大路徑長度
			adjList[p->vsub].len=GetMax(adjList[v].len+1,adjList[p->vsub].len);
			maxlen=GetMax(adjList[p->vsub].len,maxlen);
			if(!(--adjList[p->vsub].in))stack[++top]=p->vsub;
		}
	}
}

int main(){
	scanf("%d%d",&n,&e);
	for(int k=0;k<e;k++){
		scanf("%d%d",&i,&j);i--;j--;
		t=new ENode;t->vsub=j;adjList[j].in++;
		t->succ=adjList[i].fstEdge;adjList[i].fstEdge=t;
	}
	TSort();printf("%d\n",maxlen+1);//最後求的是最大路徑包含的頂點數,故需要+1
	return 0;
}

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