您的位置:首页 > 大数据 > 人工智能

POJ 3411 Paid Roads(dfs技巧)

2017-10-05 10:02 387 查看

Description

A network of m roads connects N cities (numbered from 1 to N). There may be more than one road connecting one city with another. Some of the roads are paid. There are two ways to pay for travel on a paid road i from city ai to city bi:

in advance, in a city ci (which may or may not be the same as ai);

after the travel, in the city bi.

The payment is Pi in the first case and Ri in the second case.

Write a program to find a minimal-cost route from the city 1 to the city N.

Input

The first line of the input contains the values of N and m. Each of the following m lines describes one road by specifying the values of ai, bi, ci, Pi, Ri (1 ≤ i ≤ m). Adjacent values on the same line are separated by one or more spaces. All values are integers, 1 ≤ m, N ≤ 10, 0 ≤ Pi , Ri ≤ 100, Pi ≤ Ri (1 ≤ i ≤ m).

Output

The first and only line of the file must contain the minimal possible cost of a trip from the city 1 to the city N. If the trip is not possible for any reason, the line must contain the word ‘impossible’.

Sample Input

4 5
1 2 1 10 10
2 3 1 30 50
3 4 3 80 80
2 1 2 10 10
1 3 2 10 50


Sample Output

110


题目大意

有n个城市,m条路,经过a->b时如果到过c城市,则需要付费p,否则付费r。现在询问1->n至少付费多少。

解题思路

首先需要明确题意:对于图中的某点是可以重复经过的,当a−>c+c−>a<a−>b时,就会选择先去经过c城市然后将a->b的花费从r缩减为p。例如样例的结果即为1−>2+2−>1+1−>3+3−>4。但是这样我们又会陷入一个新的困境,使用dfs进行解题时,如果一条路可以重复走,那我们不就失去了限制搜素的条件进入死循环了吗?仔细阅读题意会发现题目中限制了边数m<=10,我们每次通过第三点来缩减a->b的花费时,就会增加两条边,这样的话就代表我们至多只会通过一个点5次。即只有当一个点的访问次数<=4时,我们才会进入下一步的搜索。这样问题就得到解决了

代码实现

#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define ll long long
#define maxn 27
#define maxx 0x3f3f3f
int vis[maxn];
int ans,n,m;
struct node
{
int a,b,c,p,r;
}edge[maxn];

void dfs(int point,int cnt)
{
if(point==n&&ans>cnt)
{
ans=cnt;
return;
}
for(int i=1;i<=m;i++)
{
if(point==edge[i].a&&vis[edge[i].b]<=4)
{
vis[edge[i].b]++;
if(vis[edge[i].c])
dfs(edge[i].b,cnt+edge[i].p);
else
dfs(edge[i].b,cnt+edge[i].r);
vis[edge[i].b]--;
}
}
}

int main()
{
while(~scanf("%d %d",&n,&m))
{
memset(vis,0,sizeof(vis));
ans=maxx;
for(int i=1;i<=m;i++)
{
scanf("%d %d %d %d %d",&edge[i].a,&edge[i].b,&edge[i].c,&edge[i].p,&edge[i].r);
}
vis[1]=1;
dfs(1,0);
if(ans==maxx)
printf("impossible\n");
else
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: