Paid Roads——poj3411

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 aibiciPiRi (1 ≤ ≤ 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 ≤ ≤ 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道路数

u~v,c如果经过c则用为p否则为r 

爆搜,注意恶性递增的环,控制点访问次数不大于3

#include <iostream>
#include <string.h>
using namespace std;
int n,m;  //城市数,道路数
int vis[11];  //记录城市的访问次数,当点访问数大于等于4时退出该层dfs,然后继续搜索(防止恶性增加的环) 
int mmin;  //最小总花费
struct haha{
	int u,v;
	int c;
	int p,r;
}we[11];  //u~v,经过c时费用为p否则为r 
void dfs(int s,int minn){
	if(s==n && mmin>minn){
		mmin=minn;
		return;
	}
	for(int i=1;i<=m;i++){
		if(s==we[i].u && vis[we[i].v]<=3){//控制点访问不超过3次 
			int v=we[i].v;//下个点 
			vis[v]++;
			if(vis[ we[i].c ])
				dfs(v,minn+we[i].p);
			else
				dfs(v,minn+we[i].r);
			vis[v]--; 
		}
	}
	return;
}
 
int main(void){
	while(cin>>n>>m){
		memset(vis,0,sizeof(vis));
		mmin=99999;
		for(int i=1;i<=m;i++){
			scanf("%d %d %d %d %d",&we[i].u,&we[i].v,&we[i].c,&we[i].p,&we[i].r);
 		}
 		vis[1]=1;
		dfs(1,0);
		if(mmin==99999){
			printf("impossible\n");
		}
		else{
			printf("%d\n",mmin);
		}
	}
	return 0;
} 


猜你喜欢

转载自blog.csdn.net/doublekillyeye/article/details/81057271