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

poj 3411 Paid Roads(dfs)

2017-05-31 09:27 483 查看
Paid Roads

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 5481Accepted: 1947
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条路线。每条路线有5个值,a,b,c,p,r表示从a城到b城。假设到过c城,收费p元,否则收费r元。

如今从1到n,求最小花费。

这题主要是去过的点又回来的问题,比如例子1->2->1->3->4,从2又返回了1,因为m=10,所以一个点最多訪问3次(事实上取2也能A,感觉还是3靠谱点)

ps:刚開始记录了map[i][j]表示i到j能够走第map[i][j]条路。由于从第i到j能够有多条路,一直wa,再改就麻烦了,换成直接枚举m条路,反正m也不大。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int inf=99999999;
//int map[15][15];
int vis[15];
int n,m;
int ans;
struct node
{
int a;
int b;
int c;
int p;
int r;
}road[15];
void dfs(int u,int v)
{
if(v>ans)
return;
if(u==n)
{
if(v<ans)
{
ans=v;
// printf("  %d\n",ans);
}
return;
}
for(int i=1;i<=m;i++)
{
if(road[i].a==u&&vis[road[i].b]<=3)
{
int b=road[i].b;
vis[b]++;
if(vis[road[i].c])
{
dfs(b,v+road[i].p);
}
else
{
dfs(b,v+road[i].r);
}
vis[b]--;
}
}
return;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
ans=inf;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d%d%d",&road[i].a,&road[i].b,&road[i].c,&road[i].p,&road[i].r);
}
vis[1]=1;
dfs(1,0);
if(ans==inf)
printf("impossible\n");
else
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: