题意:有N个城市M条路,这些路必须是付费的,而且有些路有点特别,不仅可以在始终点付费,也可以在更早经过的点付费,且早付费的价钱肯定更便宜。问从城市1到城市N的最小花费。
题解:此题关键点就是一个城市可能不止经过一次,也即是最佳路径可能有环,因为我们有时为了更少花费只能先经过一点,再返回原点继续走到终点的路。
- 如果一个城市被访问n次至少需要多少条不同的边,这样做的出发点就是输入规模很小。
- 为了使边最少,我们假设被访问n次的点为城市1,且其他城市仅访问一次,要使边最少,则路径当中应该只有必要的环边。
eg:
5 7
1 2 1 1 100
2 1 1 1 100
1 3 2 1 100
3 1 3 1 100
1 4 3 1 100
4 1 4 1 100
1 5 4 1 100
- 上例就是这样一个例子,为了到达城市5,最佳路径是:1->2->1->3->1->4->1->5。则我们可以看到城市1被访问4次,不同的边有4*2-1条。利用归纳法可知:一个城市被访问n次至少需要2*n-1条边,因为2*n-1<=10,易知n<=5。所以一个城市最多能被访问5次,所以在DFS过程加入这个条件即可。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define INF 0X7FFFFFFF
class Node
{
public:
int next;
int pre;
int preCost,nextCost;
Node* nextNode;
};
class adjList
{
public:
Node** adj;
adjList(int n):adj(new Node*[n])
{
memset(adj,0,sizeof(Node*)*n);
}
int adjInsert(int nodeNo,int next,int pre,int preCost,int nextCost)
{
Node* newNode = new Node;
newNode->next = next;
newNode->pre = pre;
newNode->preCost = preCost;
newNode->nextCost = nextCost;
newNode->nextNode = adj[nodeNo];
adj[nodeNo] = newNode;
return 0;
}
};
class solve
{
private:
int N,M;
adjList* g;
int minCost;
int* vis;
public:
solve(int n,int m):N(n),M(m),g(new adjList(n+1))
{
minCost = INF;
vis = new int[N+1];
memset(vis,0,sizeof(int)*(N+1));
processIn();
DFS(1,0);
if(minCost != INF)
printf("%d\n",minCost);
else
printf("impossible\n");
}
~solve()
{
delete[] g;
delete[] vis;
}
int processIn();
int DFS(int u,int cost);
};
int solve::DFS(int u,int cost)
{
vis[u]++;
if(u == N)
{
if(minCost > cost)
{
minCost = cost;
}
return 1;
}
if(cost >= minCost)
{
return 0;
}
int v;
int tmpCost;
Node* tmpNode;
for(tmpNode = g->adj[u];tmpNode != NULL;tmpNode = tmpNode->nextNode)
{
if(vis[tmpNode->next] < 5) //根据输入一个点最多能访问的次数
{
v = tmpNode->next;
if(vis[tmpNode->pre]) //如果提前收费节点已访问,则可以花费更少继续往下走
{
tmpCost = cost+tmpNode->preCost;
}
else
{
tmpCost = cost+tmpNode->nextCost;
}
DFS(v,tmpCost);
vis[v]--; //路径更改,不经过上面DFS已经标记的点一次
}
}
return 0;
}
int solve::processIn()
{
int a,b,c,p,r;
while(M--)
{
scanf("%d%d%d%d%d",&a,&b,&c,&p,&r);
g->adjInsert(a,b,c,p,r);
}
return 0;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
solve poj_3411(n,m);
}
return 0;
}