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

poj 3411 Paid Roads(dfs)

2015-09-13 22:06 453 查看
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

直接dfs回溯找出最小的花费即可,以为n很小

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<bitset>
#include<map>
#include<vector>
#include<stdlib.h>
using namespace std;
#define ll long long
#define eps 1e-10
#define MOD 1000000007
#define N 26
#define inf 1e12
int n,m;

struct Node{
int b,c,p,r;
};
vector<Node> node
;
int ans;
int vis
;
void dfs(int u,int cost){
vis[u]++;
if(cost>=ans) return;
if(u==n){
if(cost<ans)
ans=cost;
return;
}

int size=node[u].size();
for(int i=0;i<size;i++){
int v=node[u][i].b;
if(vis[v]<=3){
int t=99999;
if(vis[node[u][i].c] && t>node[u][i].p){
t=node[u][i].p;
}
if(t>node[u][i].r){
t=node[u][i].r;
}
dfs(v,t+cost);
vis[v]--;
}
}

}
int main()
{
while(scanf("%d%d",&n,&m)==2){
for(int i=0;i<N;i++) node[i].clear();
//scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
int a,b,c,p,r;
scanf("%d%d%d%d%d",&a,&b,&c,&p,&r);
Node tmp;
//tmp.a=a;
tmp.b=b;
tmp.c=c;
tmp.p=p;
tmp.r=r;
node[a].push_back(tmp);
}
memset(vis,0,sizeof(vis));
ans=99999;
dfs(1,0);
if(ans==99999) printf("impossible\n");
else printf("%d\n",ans);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: