程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> poj3411

poj3411

編輯:C++入門知識

題目鏈接:

http://poj.org/problem?id=3411

題目:

Paid Roads Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 5080 Accepted: 1784

Description

A network of m roads connects N cities (numbered from 1 toN). 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 roadi from city ai to city bi:

in advance, in a city ci (which may or may not be the same asai);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 ofai, 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,PiRi (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 cityN. 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 這個題目的意思是有兩種付費方式。

1:如果以前經過c城市,那麼就在c城市付費。。

2:如果沒有經過,那麼就在b城市付費。。

還有注意題目中的數據為m<10,所以每個點最多走3次。。

因為成環的話那麼最少3個點,則最少3路。所以最多走3次。。。

故應用int vis[ manx]。。。

然後dfs回溯。。。

所以代碼為:

#include
#include
#include
#define INF 0x3f3f3f3f
const int maxn=10+10;
int vis[maxn];
int min_cost,fee;
int n,m;
struct node
{
    int a,b,c,p,r;
}e[maxn];
void dfs(int x,int fee)
{
    if(x==n&&min_cost>fee)
    {
        min_cost=fee;
        return;
    }
    if(x==n)
        return;
    for(int i=1;i<=m;i++)
    {
        if(e[i].a==x&&vis[e[i].b]<3)
        {
            vis[e[i].b]++;
            if(vis[e[i].c])
                dfs(e[i].b,fee+e[i].p);
            else
                dfs(e[i].b,fee+e[i].r);
            vis[e[i].b]--;
        }
    }
}

int main()
{
   while(scanf("%d %d",&n,&m)!=EOF)
   {
       memset(vis,0,sizeof(vis));
       min_cost=INF;
       for(int i=1;i<=m;i++)
       {
           scanf("%d%d%d%d%d",&e[i].a,&e[i].b,&e[i].c,&e[i].p,&e[i].r);
       }
       vis[1]=1;
       dfs(1,0);
       if(min_cost!=INF)
          printf("%d\n",min_cost);
       else
         printf("impossible\n");
   }
   return 0;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved