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

【POJ3411】-Paid Roads 搜索剪枝

2016-06-24 14:36 441 查看

Time Limit: 1000MS Memory Limit: 65536K

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

Source

Northeastern Europe 2002, Western Subregion

题意:有n个城市,m条道路(有向),对与一条道路有两种状态,如果经过c花费为p,没有经过花费为r,求从1到n的最少的花费。

思路:路是有向的,并且对于同一条路我们是可以重复走的,那么重复走的原因是由于可以开启新的点,使得总的花费最短,那么我们可以限制一条路走的次数,每一次重复走与点有关,我们可以限制走的次数不超过点的个数。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <algorithm>

using namespace std;

const int INF = 0x3f3f3f3f;

typedef struct node
{
int c,p,r;
}Ro;

Ro R[150];

int n,m;

int u,v;

vector<pair<int,int> >E[110];

int visp[110],visr[110];

int ans;

void dfs(int u,int len)
{
if(len>ans)
{
return ;
}
if(u == n)
{
ans = min(ans,len);

return ;
}
for(int i = 0;i<E[u].size();i++)
{
if(visr[E[u][i].second]<n)
{
visr[E[u][i].second]++;

if(!visp[R[E[u][i].second].c])
{
visp[E[u][i].first] ++;

dfs(E[u][i].first,len+R[E[u][i].second].r);
}
else
{
visp[E[u][i].first] ++;

dfs(E[u][i].first,len+R[E[u][i].second].p);
}

visr[E[u][i].second]--;

visp[E[u][i].first] --;

}
}
}

int main()
{
while(~scanf("%d %d",&n,&m))
{
for(int i = 1;i<=n;i++)
{
E[i].clear();
}

for(int i = 0;i<m;i++)
{
scanf("%d %d",&u,&v);

scanf("%d %d %d",&R[i].c,&R[i].p,&R[i].r);

E[u].push_back(make_pair(v,i));
}

memset(visp,0,sizeof(visp));

memset(visr,0,sizeof(visr));

visp[1] = 1;

ans = INF;

dfs(1,0);

if(ans == INF)
{
printf("impossible\n");
}
else printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: