[Title] cloak brush

Directed graph, each point a little right, the way to find all paths, the maximum value of the maximum and minimum path difference

20%,N<=50

40%,N<=100

60%,N<=1000

Further 20%, acyclic FIG.

100%,N<=100 000,M<=500 000

Right point are positive integers of type int

 

60 minutes algorithm:

Of course, it is to practice violence, but that violence I wa many times,

The highest score of 60

One way to learn: enumeration path, all directly from the end of the enumeration

#include<cstdio>
#include<cstdlib>
#include<vector>
using namespace std;
int n,m;
const int N=1003;
vector <int> g[N];
int d[N],ans;

bool vis[N];
void dfs(int u,int ed,int mx,int mn)
{
    if(u==ed)
    {
        ans=max(ans,mx-mn);
        return ;
    }
    
    int sz=g[u].size() ;
    for(int i=0;i<sz;i++)
    {
        int v=g[u][i];
        if(vis[v]) continue;
        
        vis[v]=true;
        dfs(v,ed,max(mx,d[v]),min(mn,d[v]));
        vis[v]=false;
    }
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&d[i]);
    int x,y;
    while(m--)
    {
        scanf("%d%d",&x,&y);
        g[x].push_back(y); 
    }
    
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(i==j) continue;
            
            vis[i]=true;
            dfs(i,j,d[i],d[i]);
            vis[i]=false;
        }
    }
    
    printf("%d\n",ans);
    return 0;
}

Then I improved a bit,

Find all paths, I enumerate only a starting point

Speed ​​30ms-> 4ms (first 6 points)

Then 6 points -> 8 points

ヽ (¯ ▽ ¯) و

void dfs(int u,int mx,int mn)
{
    int sz=g[u].size() ;
    bool conti=false;
    for(int i=0;i<sz;i++)
    {
        int v=g[u][i];
        if(vis[v]) continue;
        
        conti=true;
        vis[v]=true;
        dfs(v,max(mx,d[v]),min(mn,d[v]));
        vis[v]=false;
    }
    
    if(!conti)
        ans=max(ans,mx-mn);
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&d[i]);
    int x,y;
    while(m--)
    {
        scanf("%d%d",&x,&y);
        g[x].push_back(y); 
    }
    
    for(int i=1;i<=n;i++)
    {
        vis[i]=true;
        dfs(i,d[i],d[i]);
        vis[i]=false;
    }
    
    printf("%d\n",ans);
    return 0;
}

Well think again, what is the timeout repetitive operations, resulting?

Probably a multiple access path, such as 5-> 4-> 3-> 2-> 1

Pressing the program, it was the five times to enter dfs

So in fact the best from 5 to enter,

But the topic that ring data have, ah, how do

 

So we have to shrink tarjan point

Write tomorrow

Guess you like

Origin www.cnblogs.com/xwww666666/p/11410101.html