Problem
Describtion
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 output 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'.
Example
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
Output:
110
Solution
思路
显然我们看到题目就像状压,然后发现状态会很难设,因为样例分析可得,1->2->1->3->4这样子是最优的,所以我们可以采用dfs,又因为m<=10,所以每一个点最多经过4次(鸽巢原理),然后就可以暴力求正解了.
Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<iostream>
#define ll long long
#define re register
using namespace std;
inline int gi(){
int f=1,sum=0;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
return f*sum;
}
int a[20],b[20],c[20],p[20],r[20],S,n,m,ans,vis[1000010];
void dfs(int u,int s){
if(u==n){
ans=min(ans,s);return;
}
for(re int i=1;i<=m;i++)
if(a[i]==u && vis[b[i]]<4){
vis[b[i]]++;
dfs(b[i],vis[c[i]]?s+p[i]:s+r[i]);
vis[b[i]]--;
}
}
int main(){
n=gi();m=gi();
for(re int i=1;i<=m;i++){
a[i]=gi();b[i]=gi();c[i]=gi();p[i]=gi();r[i]=gi();
}
ans=2147483647;
dfs(1,0);
if(ans==2147483647)puts("impossible");
else printf("%d
",ans);
return 0;
}