其他分享
首页 > 其他分享> > 清华数据结构PA6——旅行商(TSP)

清华数据结构PA6——旅行商(TSP)

作者:互联网

题目:https://dsa.cs.tsinghua.edu.cn/oj/problem.shtml?id=1147

思路不算难:对图进行拓扑排序,在这个过程中利用动态规划对最大路径进行计算。

#include<iostream>
#define MAXSIZE 1000000
#define max(a,b) a>b?a:b
using namespace std;

struct edge
{
	int adjvex = 0;
	edge* next;
};

struct vertex
{
	int path = 0;
	int in = 0;
	edge* firstedge=NULL;
};


int maxpath = 0;
int top = 0;
int n, m, i, j;
edge* temp=NULL;
void toposort(int* stack, vertex* adjlist)
{
	for (int k = 0; k < n; k++)
	{
		if (!adjlist[k].in)
		{
			stack[++top] = k;
		}
	}
	while (top)
	{
		int x = stack[top--];
		for (edge* temp1 = adjlist[x].firstedge; temp1; temp1 = temp1->next)
		{
			adjlist[temp1->adjvex].path = max(adjlist[x].path + 1, adjlist[temp1->adjvex].path);
			maxpath = max(adjlist[temp1->adjvex].path, maxpath);
			if (!(--adjlist[temp1->adjvex].in))
			{
				stack[++top] = temp1->adjvex;
			}
		}
	}
}

int main()
{
	scanf("%d%d", &n, &m);
	vertex* adjlist=new vertex[n];
	int* stack = new int[n];
	for (int k = 0; k < m; k++)
	{
		scanf("%d%d", &i, &j);
		i--;j--;
		temp = new edge;
		temp->adjvex = j;
		adjlist[j].in++;
		temp->next = adjlist[i].firstedge;
		adjlist[i].firstedge = temp;
	}
	toposort(stack, adjlist);
	printf("%d", maxpath + 1);
}

标签:adjlist,PA6,int,adjvex,temp1,edge,数据结构,stack,TSP
来源: https://blog.csdn.net/Armavilla/article/details/98785439