Shortest UOJ # 494. K point

[Title Description:

Given a point n and m edges directed graph, there are k markers, starting from the requirements specified in an arbitrary order through all reach the end of the predetermined markers, asked how the shortest distance Yes.

[Input Description:

The first line of five integers n, m, k, s, t, represents the number of points, the number of edges, the number of markers, starting number, the end serial number.

Next each row 3 line m integers x, y, z, expressed a length from x to y for z directed edge.

The next two lines each k represents an integer number markers.

[Output] Description:

Output an integer, represents the shortest distance, -1 if not feasible output.

[Sample input]:

3 3 2 1 1
1 2 1
2 3 1
3 1 1
2
3

[] Sample output:

3

[Sample] Description:

Path 1-> 2-> 3-> 1.

[Time limit, and the range of data Description:

Time: 1s space: 256M

20% of the data n <= 10.

50% of the data n <= 1000.

Another 20% of the data of k = 0.

100% data n <= 50000, m <= 100000,0 <= k <= 10,1 <= z <= 5000.

download

Ideas:

First build a adjacency table, pitted again SPFA shortest, then burst search about DFS, ans (for the flag and variable) for the minimum, and finally determine whether or not solvable ans

 

Code:

#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int N=100010;
const long long oo=0x7ffffffffffffff;

struct no {
	long long to,nxt,dis;
} map[N];

queue<long long> q;

long long k,t,ans=oo;
long long n,m,s,x,y,z;
long long vis[N],tot,head[N];
long long p[N],dis[N],f[20][20];

void add(long long u,long long v,long long w) {
	tot++;
	map[tot].to=v;
	map[tot].nxt=head[u];
	map[tot].dis=w;
	head[u]=tot;
}

void spfa(long long s) {
	memset(dis,0x3f,sizeof(dis));
	dis[s]=0;
	q.push(s);
	while(q.size()) {
		long long tmp=q.front();
		q.pop();
		for(long long i=head[tmp]; i; i=map[i].nxt) {
			long long v=map[i].to;
			if(dis[v]>dis[tmp]+map[i].dis) {
				dis[v]=dis[tmp]+map[i].dis;
				q.push(v);
			}
		}
	}
}

void dfs(long long s,long long v,long long cur) {
	if(cur==0) {
		ans=min(ans,v+f[s][k+2]);
		return;
	}
	for(long long i=1; i<=k; i++) {
		if(vis[p[i]])
			continue;
		vis[p[i]]=1;
		dfs(i,v+f[s][i],cur-1);
		vis[p[i]]=0;
	}
}

int main () {
	scanf("%d%d%d%d%d",&n,&m,&k,&s,&t);
	for(long long i=1; i<=m; i++) {
		scanf("%d%d%d",&x,&y,&z);
		add(x,y,z);
	}
	for(long long i=1; i<=k; i++)
		scanf("%d",&p[i]);
	p[k+1]=s;
	p[k+2]=t;
	k+=2;
	memset(f,0x3f,sizeof(f));
	for(long long i=1; i<=k; i++) {
		spfa(p[i]);
		f[i][i]=0;
		for(long long j=1; j<=k; j++) {
			if(i==j)
				continue;
			f[i][j]=min(f[i][j],dis[p[j]]);
		}
	}
	k-=2;
	dfs(k+1,0,k);
	printf("%lld\n",ans>=oo?-1:ans);
	return 0;
}

 

Guess you like

Origin www.cnblogs.com/mysh/p/11351226.html