Dijkstra(第二关键词最优),路径保存DFS

Travel Plan (30)

第二关键词最优,只要在relax处增加一个条件:当第一关键词两边相等时,对第二关键词进行松弛操作

代码:(这是目前最完美的版本了)

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define inf 0x3f3f3f3f
int N,M,S,D;

struct node{
    int num;  //编号
    int d;  //最小距离估计
    int cost;  //最小花费估计
    int pi; //前驱
    bool operator < (const node & re) const{
        return re.d<d;
    }
};
node nodes[505];

struct side{
    int v;   //指向的结点编号
    int dis;   //该条边的权
    int cost;  
    side(int _v,int _dis,int _cost):v(_v),dis(_dis),cost(_cost){}
};
vector<side>sides[505];

bool can[505];
void dijkstra()
{
    for(int i=0;i<N;i++) nodes[i].num=i,nodes[i].d=inf,nodes[i].cost=inf;
    nodes[S].d=0;
    nodes[S].cost=0;
    priority_queue<node>Q;
    Q.push(nodes[S]);
    while(!Q.empty())
    {
        node n=Q.top(); Q.pop();
        if(can[n.num]) continue;
        can[n.num]=1;
        for(int i=0;i<sides[n.num].size();i++)
        {
            int u=n.num,v=sides[n.num][i].v;
            int w=sides[n.num][i].dis,c=sides[n.num][i].cost;
            //第二关键词最优
            if(nodes[v].d>nodes[u].d+w || 
              (nodes[v].d==nodes[u].d+w && nodes[v].cost>nodes[u].cost+c)){
                nodes[v].d=nodes[u].d+w;
                nodes[v].cost=nodes[u].cost+c;
                nodes[v].pi=u;
            }
            Q.push(nodes[v]);
        }
    }
}

void print(int n)
{
    if(n!=S) print(nodes[n].pi);
    cout<<n<<" ";
}

int main()
{
    cin>>N>>M>>S>>D;
    for(int i=0;i<M;i++){
        int c1,c2,dis,cost;
        cin>>c1>>c2>>dis>>cost;
        sides[c1].push_back(side(c2,dis,cost));
        sides[c2].push_back(side(c1,dis,cost));
    }
    dijkstra();
    print(D);
    cout<<nodes[D].d<<" "<<nodes[D].cost<<endl;
    return 0;
}

  

input

11 19
10 2 3
10 1 2
10 3 4
1 2 3
1 5 2
1 4 7
2 5 9
2 6 2
3 6 2
6 5 1
6 8 5
6 9 1
9 8 2
9 11 2
4 8 3
4 7 3
7 11 3
8 11 2
5 8 3
10 11

output

最短路径长度:8
路径信息:10 2 6 9 11

 1 #include <iostream>
 2 #include <vector>
 3 #include <queue>
 4 using namespace std;
 5 const int INF=0x3f3f3f3f;
 6 
 7 int n,m;
 8 int S,T;
 9 struct node{//
10     int u;//节点编号
11     int dict;//与源点距离
12     int pi;//前驱
13     //取反,变成小顶堆
14     bool operator < (const node & re) const{
15         return dict>re.dict;
16     }
17 };
18 node nodes[100];
19 
20 struct side{//
21     int v;//该边指向的下一个节点
22     int w;//边权
23     side(int _v,int _w):v(_v),w(_w){}
24 };
25 vector<side>sides[100];//图的邻接表表示法
26 
27 int flag[100];//标记,访问过的点不再访问
28 void dij()
29 {
30     //对节点信息初始化,并在之后的循环中更新节点信息
31     for(int i=1;i<=n;i++)
32     {
33         nodes[i].u=i;
34         nodes[i].dict=INF;//初始距离无穷大
35         nodes[i].pi=0;//无前驱
36     }
37     nodes[S].dict=0;//源点
38 
39     priority_queue<node>Q;//最大堆
40     //当前活节点只有S,加入优先队列
41     Q.push(nodes[S]);
42 
43     while(!Q.empty())//一直到没有活节点为止
44     {
45         node t=Q.top(); Q.pop();
46         flag[t.u]=1;//访问标记
47         //遍历该活结点的扩展节点
48         for(int i=0;i<sides[t.u].size();++i)
49         {
50             //检测是否需要更新
51             int v=sides[t.u][i].v;//当前扩展点的编号
52             int w=sides[t.u][i].w;//
53             if(nodes[v].dict>nodes[t.u].dict+w){
54                 //更新节点信息
55                 nodes[v].dict=nodes[t.u].dict+w;
56                 nodes[v].pi=t.u;
57             }
58             if(!flag[v]) Q.push(nodes[v]);//加入活结点
59         }
60     }
61 }
62 
63 void print_path(int x)
64 {
65     if(x==0) return ;
66     print_path(nodes[x].pi);
67     cout<<x<<" ";
68 }
69 
70 void print()
71 {
72     cout<<"最短路径长度:"<<nodes[T].dict<<endl;
73     cout<<"路径信息:";
74     print_path(T);
75 }
76 
77 int main()
78 {
79     cin>>n>>m;
80     //构建图
81     for(int i=1;i<=m;i++){
82         int a,b,c; cin>>a>>b>>c;
83         sides[a].push_back(side(b,c));
84     }
85     cin>>S>>T;
86     dij();
87     print();
88     return 0;
89 }
详细注释版本

1111 Online Map (30 分)

题目意思参考(不想写...): 1111. Online Map (30)-PAT甲级真题(Dijkstra + DFS)

标准的Dijkstra,两次,都是第二关键词最优

    (写了1小时...还是太慢了)

  1 #include<iostream>
  2 #include<map>
  3 #include<vector>
  4 #include<algorithm>
  5 #include<queue>
  6 using namespace std;
  7 #define inf 0x3f3f3f3f
  8 int N,M;
  9 int S,D;
 10 struct node1{
 11     int id;//编号
 12     int d;//路径最小估计
 13     int t;//最小时间估计
 14     int fa;//前驱
 15     bool operator < (const node1& re) const{
 16         return re.d<d;
 17     }
 18 };
 19 node1 No1[509];
 20 
 21 struct node2{
 22     int id;//编号
 23     int t;//时间最小估计
 24     int num;//最小站点估计
 25     int fa;
 26     bool operator < (const node2& re) const{
 27         return re.t<t;
 28     }
 29 };
 30 node2 No2[509];
 31 
 32 struct side{
 33     int v;
 34     int dis;
 35     int time;
 36     side(int _v,int _d,int _t):v(_v),dis(_d),time(_t){}
 37 };
 38 vector<side>G[509];
 39 
 40 int can1[506];
 41 void dij1()//距离最短
 42 {
 43     for(int i=0;i<N;i++) No1[i].id=i,No1[i].fa=-1,No1[i].d=inf,No1[i].t=inf;
 44     No1[S].d=0;
 45     No1[S].t=0;
 46     priority_queue<node1>Q;
 47     Q.push(No1[S]);
 48     while(!Q.empty())
 49     {
 50         node1 t=Q.top(); Q.pop();
 51         if(can1[t.id]) continue;
 52         can1[t.id]=1;
 53         for(int i=0;i<G[t.id].size();i++)
 54         {
 55             int u=t.id,v=G[t.id][i].v,dis=G[t.id][i].dis,time=G[t.id][i].time;
 56             if(No1[v].d>No1[u].d+dis || (No1[v].d==No1[u].d+dis && No1[v].t>No1[u].t+time) ){
 57                 No1[v].d=No1[u].d+dis;
 58                 No1[v].t=No1[u].t+time;
 59                 No1[v].fa=u;
 60             }
 61             Q.push(No1[v]);
 62         }
 63     }
 64 }
 65 
 66 int can2[506];
 67 void dij2()//距离最短
 68 {
 69     for(int i=0;i<N;i++) No2[i].id=i,No2[i].fa=-1,No2[i].num=inf,No2[i].t=inf;
 70     No2[S].t=0;
 71     No2[S].num=1;
 72     priority_queue<node2>Q;
 73     Q.push(No2[S]);
 74     while(!Q.empty())
 75     {
 76         node2 t=Q.top(); Q.pop();
 77         if(can2[t.id]) continue;
 78         can2[t.id]=1;
 79         for(int i=0;i<G[t.id].size();i++)
 80         {
 81             int u=t.id,v=G[t.id][i].v,time=G[t.id][i].time;
 82             if(No2[v].t>No2[u].t+time || (No2[v].t==No2[u].t+time && No2[v].num>No2[u].num+1) ){
 83                 No2[v].t=No2[u].t+time;
 84                 No2[v].num=No2[u].num+1;
 85                 No2[v].fa=u;
 86             }
 87             Q.push(No2[v]);
 88         }
 89     }
 90 }
 91 vector<int>ans1;
 92 void find_path1(int n)
 93 {
 94     if(n!=-1)
 95         ans1.push_back(n);
 96     else return ;
 97     find_path1(No1[n].fa);
 98 }
 99 
100 vector<int>ans2;
101 void find_path2(int n)
102 {
103     if(n!=-1)
104         ans2.push_back(n);
105     else return ;
106     find_path2(No2[n].fa);
107 }
108 
109 int compare()
110 {
111     if(ans1.size()!=ans2.size()) return 0;
112     for(int i=0;i<ans1.size();i++){
113         if(ans1[i]!=ans2[i]) return 0;
114     }
115     return 1;
116 }
117 
118 void print_path1()
119 {
120     int n=ans1.size();
121     for(int i=n-1;i>=0;i--){
122         cout<<ans1[i];
123         if(i!=0){
124             cout<<" -> ";
125         }
126     }
127     cout<<endl;
128 }
129 
130 void print_path2()
131 {
132     int n=ans2.size();
133     for(int i=n-1;i>=0;i--){
134         cout<<ans2[i];
135         if(i!=0){
136             cout<<" -> ";
137         }
138     }
139     cout<<endl;
140 }
141 
142 int main()
143 {
144     cin>>N>>M;
145     for(int i=1;i<=M;i++)
146     {
147         int a1,a2,a3,a4,a5;
148         cin>>a1>>a2>>a3>>a4>>a5;
149         G[a1].push_back(side(a2,a4,a5));
150         if(a3==0) G[a2].push_back(side(a1,a4,a5));
151     }
152     cin>>S>>D;
153     dij1();
154     dij2();
155     find_path1(D);
156     find_path2(D);
157     int flag=compare();
158     if(flag){
159         cout<<"Distance = "<<No1[D].d<<"; Time = "<<No2[D].t<<": ";
160         print_path1();
161     }
162     else{
163         cout<<"Distance = "<<No1[D].d<<": ";
164         print_path1();
165         cout<<"Time = "<<No2[D].t<<": ";
166         print_path2();
167     }
168     return 0;
169 }
Dij+路径
All Roads Lead to Rome (30)
  • 热度指数:5519时间限制:1秒空间限制:65536K
Indeed there are many different tourist routes from our city to Rome. You are supposed to find your clients the route with the least cost while gaining the most happiness.

输入描述:
Each input file contains one test case.  For each case, the first line contains 2 positive integers N (2<=N<=200), the number of cities, and K, the total number of routes between pairs of cities; followed by the name of the starting city.  The next N-1 lines each gives the name of a city and an integer that represents the happiness one can gain from that city, except the starting city.  Then K lines follow, each describes a route between two cities in the format "City1 City2 Cost".  Here the name of a city is a string of 3 capital English letters, and the destination is always ROM which represents Rome.


输出描述:
For each test case, we are supposed to find the route with the least cost.  If such a route is not unique, the one with the maximum happiness will be recommended.  If such a route is still not unique, then we output the one with the maximum average happiness -- it is guaranteed by the judge that such a solution exists and is unique.
Hence in the first line of output, you must print 4 numbers: the number of different routes with the least cost, the cost, the happiness, and the average happiness (take the integer part only) of the recommended route. Then in the next line, you are supposed to print the route in the format "City1->City2->...->ROM".
示例1

输入

6 7 HZH
ROM 100
PKN 40
GDN 55
PRS 95
BLN 80
ROM GDN 1
BLN ROM 1
HZH PKN 1
PRS ROM 2
BLN HZH 2
PKN GDN 1
HZH PRS 1

输出

3 3 195 97
HZH->PRS->ROM

分析

  输入城市数N,K条城市之间的连接,起点城市名称,后面N-1行为其余的城市名+其幸福值(起点城市无幸福值),再K行为城市间道路信息(City1,City2,Cost)。

  输出从起点城市到ROM城市的最低总Cost的方案数,最低总Cast,happiness,平均幸福值ave=总幸福值/经过城市数(起点城市不算)。

    再打印具体路径。

  思路:首先给城市编号,这里设置起点城市为0,终点为num["ROM"]。然后Dijkstra套路一下,最后DFS遍历每条最短路径,求出符合题意的

代码:

#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <stack>
using namespace std;
#define ll long long
const ll inf=0x3f3f3f3f3f3f3f3f;
ll N,K;
string Sp;//开始城市 
map<string,ll>num;//城市编号 
map<ll,string>num1;//城市编号 
ll hap[206];//城市幸福值 
ll d[206];
ll B[206];
vector<ll>fa[206];//父节点 

struct node{
    ll v,edge;
    node(ll _v,ll _e):v(_v),edge(_e){}
};
vector<node>G[40007];

struct TT{
    ll d,v;
    TT(ll _d,ll _v):d(_d),v(_v){}
    bool operator < (const TT& con) const{
        return d>con.d;
    }
};

void Dijkstra()
{
    priority_queue<TT>Q;
    for(ll i=0;i<N;i++) d[i]= (i==0?0:inf);
    Q.push(TT(0,0));
    while(!Q.empty())
    {
        TT x=Q.top();    Q.pop();
        if(B[x.v]) continue;
        B[x.v]=1;
        for(ll i=0;i<G[x.v].size();i++)//对每条边松弛 
        {
            ll u=x.v;    ll v=G[u][i].v;
            ll dis=G[u][i].edge;
            if(d[v]>(d[u]+dis)){
                d[v]=d[u]+dis;
                fa[v].clear();    fa[v].push_back(u);
                Q.push(TT(d[v],v));
            }
            else if(d[v]==(d[u]+dis)){
                fa[v].push_back(u);
                Q.push(TT(d[v],v));
            }
            
        }
    }
}
stack<ll>VV;
ll max_hap=-inf;//最高happiness 
ll ave;//最高hap所对应的平均hap
ll anss=0;//路径数 
void DFS(ll HAP,ll n,stack<ll>st,ll sum)
{
    HAP+=hap[n];
    st.push(n);
    sum++;
    if(n==0)//到源点 
    { 
        anss++;
        if(HAP>max_hap || (HAP==max_hap && HAP/(sum-1)>ave)){
            VV=st;
            max_hap=HAP;
            ave=HAP/(sum-1); 
        }
    }
    
    for(ll i=0;i<fa[n].size();i++)
    {
        DFS(HAP,fa[n][i],st,sum);
    }
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    cin>>N>>K>>Sp;
    num[Sp]=0;
    num1[0]=Sp; 
    for(ll i=1;i<N;i++) {
        string s;
        cin>>s;    
        num[s]=i;//编号 
        num1[i]=s;
        cin>>hap[i];
    }
    for(ll i=1;i<=K;i++)
    {
        string c1,c2;    int cost;
        cin>>c1>>c2>>cost;
        G[num[c1]].push_back(node(num[c2],cost));
        G[num[c2]].push_back(node(num[c1],cost));
    }
    Dijkstra();
    stack<ll>st1;
    DFS(0,num["ROM"],st1,0);
    cout<<anss<<" "<<d[num["ROM"]]<<" "<<max_hap<<" "<<ave<<endl;
    while(!VV.empty()){
        ll t=VV.top();    VV.pop();
        cout<<num1[t];
        if(VV.size()>0)    cout<<"->";
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/liuyongliu/p/11207718.html