Preparing for a quick refresher --day13

Bellman Ford

N-1 for wheel (up to layer n-1, that is, [0, n-2]), all sides of each relaxation, but also the relaxation If after, loop described negative

This complexity is O (VE), dijkstra is O (V ^ 2 + E)

  • Use the adjacent table instead of adjacency matrix, adjacency matrix complexity will increase
  • In the adjacent table edge, when used, determines good Adj [u] [j] is the corresponding side, d [Adj [u] [j] .v] corresponding end edge d, intermediate distance dis is Adj [u] [ j] .dis, this easy to mistake
  • Use set to use the insert, as several rounds of relaxation will certainly be repeated repeatedly access point, so use set
  • In equal time, num modification is cleared recalculated. (This can also lead to not be completed, and all pre deposit is recalculated after the end)
  • Initial num [st] = 1;
#include<stdio.h>
#include<string.h>
#include<set>
#include<vector>
using namespace std;
int n,m,st,ed;
const int INF=10000;
int d[1000],w[1000],num[1000];//w代表累计,num是路径数
set<int>pre[1000];
int weight[1000]={0};
struct Node{
    int v;
    int dis;
    Node(int tempv,int tempdis)
    {
        v=tempv;
        dis=tempdis;
    }
};
vector<Node>Adj[1000];
void Bellman(int st)
{
    fill(d,d+n,INF);
    memset(num,0,sizeof(num));
    for(int i=0;i<=n-1;i++)
        w[i]=weight[i];
    /*memset(w,0,sizeof(w));
    w[st]=weight[st];*/
    d[st]=0;
    num[st]=1;
    for(int i=0;i<n-1;i++)
    {
        for(int u=0;u<=n-1;u++)
        {
            for(int j=0;j<Adj[u].size();j++)
            {
                int temp=Adj[u][j].v;
                if(d[temp]>d[u]+Adj[u][j].dis)
                {
                    pre[temp].clear();
                    pre[temp].insert(u);
                    w[temp]=w[u]+weight[temp];
                    d[temp]=d[u]+Adj[u][j].dis;
                }
                else if(d[temp]==d[u]+Adj[u][j].dis)
                {
                    pre[temp].insert(u);
                    w[temp]=max(w[temp],(w[u]+weight[temp]));
                    set<int>::iterator it=pre[temp].begin();
                    num[temp]=0;
                    for(it=pre[temp].begin();it!=pre[temp].end();it++)
                    {
                        num[temp]+=num[*it];
                    }
                }
            }
        }
    }
}
int main()
{
    scanf("%d %d %d %d",&n,&m,&st,&ed);
    for(int i=0;i<=n-1;i++)
        scanf("%d",&weight[i]);
    for(int i=1;i<=m;i++)
    {
        int temp1,temp2,temp3;
        scanf("%d %d %d",&temp1,&temp2,&temp3);
        Adj[temp1].push_back(Node(temp2,temp3));
        Adj[temp2].push_back(Node(temp1,temp3));
    }
    Bellman(st);
    printf("%d %d",num[ed],w[ed]);
    return 0;
}
View Code

 A1003 code.

Guess you like

Origin www.cnblogs.com/tingxilin/p/12483870.html