1. 程式人生 > 其它 >Cow Relays G

Cow Relays G

題目描述

For their physical fitness program, N (2 ≤ N ≤ 1,000,000) cows have decided to run a relay race using the T (2 ≤ T ≤ 100) cow trails throughout the pasture.

Each trail connects two different intersections (1 ≤ I1i ≤ 1,000; 1 ≤ I2i ≤ 1,000), each of which is the termination for at least two trails. The cows know the lengthi of each trail (1 ≤ lengthi  ≤ 1,000), the two intersections the trail connects, and they know that no two intersections are directly connected by two different trails. The trails form a structure known mathematically as a graph.

To run the relay, the N cows position themselves at various intersections (some intersections might have more than one cow). They must position themselves properly so that they can hand off the baton cow-by-cow and end up at the proper finishing place.

Write a program to help position the cows. Find the shortest path that connects the starting intersection (S) and the ending intersection (E) and traverses exactly N cow trails.

輸入格式

* Line 1: Four space-separated integers: N, T, S, and E

* Lines 2..T+1: Line i+1 describes trail i with three space-separated integers: lengthi , I1i , and I2i

輸出格式

* Line 1: A single integer that is the shortest distance from intersection S to intersection E that traverses exactly N cow trails.

樣例 #1

樣例輸入 #1

2 6 6 4
11 4 6
4 4 8
8 4 9
6 6 8
2 6 9
3 8 9

樣例輸出 #1

10

有T條邊連起來的圖最多T+1個點,可以對所有點進行離散化。點的個數是T級別的。

首先有一個暴力的思路就是迴圈n次Floyd,然後輸出s到e的距離。複雜度\(O(nT^3)\).\(T^3\)很難優化,考慮怎麼優化\(n\)

發現Floyd的過程似乎是可以通過倍增來實現的。首先預處理出在\(n=2^i\)時任意兩點之間的距離,然後把n拆成二進位制數一個一個鬆弛上去。複雜度\(O(T^3logn)\),可以通過此題。

#include<bits/stdc++.h>
using namespace std;
int n,t,s,e,u[105],v[105],w[105],m,dp[25][205][205],f[2][205][205],c,lsh[205],fa[1005],x,y;
int find(int x)
{
	if(fa[x]==x)
		return x;
	return fa[x]=find(fa[x]);
}
int main()
{
	memset(dp,0x3f,sizeof(dp));
	memset(f,0x3f,sizeof(f)); 
	scanf("%d%d%d%d",&t,&m,&s,&e);
	for(int i=1;i<=1000;i++)
		fa[i]=i;
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d%d",w+i,u+i,v+i);
		fa[find(u[i])]=find(v[i]);
	}
	for(int i=1;i<=1000;i++)
		if(find(i)==find(s))
			lsh[++n]=i;	
	for(int i=1;i<=n;i++)
		f[1][i][i]=0;
	for(int i=1;i<=m;i++)
	{
		x=lower_bound(lsh+1,lsh+n+1,u[i])-lsh;
		y=lower_bound(lsh+1,lsh+n+1,v[i])-lsh;
		if(lsh[x]==u[i]&&lsh[y]==v[i])
			dp[0][x][y]=dp[0][y][x]=min(dp[0][x][y],w[i]);
	}
	for(int p=1;(1<<p)<=t;p++)
	{
		for(int k=1;k<=n;k++)
		{
			for(int i=1;i<=n;i++)
			{
				for(int j=1;j<=n;j++)
				{
					dp[p][i][j]=min(dp[p][i][j],dp[p-1][i][k]+dp[p-1][k][j]);
				}
			}
		}
	}
	for(int p=0;(1<<p)<=t;p++)
	{
		if(t&(1<<p))
		{
			for(int k=1;k<=n;k++)
			{
				for(int i=1;i<=n;i++)
				{
					for(int j=1;j<=n;j++)
					{
						f[c][i][j]=min(f[c][i][j],f[!c][i][k]+dp[p][k][j]);
					}
				}
			}
			c^=1;
			memset(f[c],0x3f,sizeof(f[c]));
		}
	}
	printf("%d",f[!c][lower_bound(lsh+1,lsh+n+1,s)-lsh][lower_bound(lsh+1,lsh+n+1,e)-lsh]);
	return 0;
}