Jungle Roads

Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 36699 Accepted: 17228 Description


The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.

Input

The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, capitalized. Each data set is completed with n-1 lines that start with village labels in alphabetical order. There is no line for the last village. Each line for a village starts with the village label followed by a number, k, of roads from this village to villages with labels later in the alphabet. If k is greater than 0, the line continues with data for each of the k roads. The data for each road is the village label for the other end of the road followed by the monthly maintenance cost in aacms for the road. Maintenance costs will be positive integers less than 100. All data fields in the row are separated by single blanks. The road network will always allow travel between all the villages. The network will never have more than 75 roads. No village will have more than 15 roads going to other villages (before or after in the alphabet). In the sample input below, the first data set goes with the map above.
Output

The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages. Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit.
Sample Input

9
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
3
A 2 B 10 C 40
B 1 C 20
0
Sample Output

216
30

题目大意:在n个点修路,每条路的权就是费用,问你删去几条边后,保持联通图的最小权值是多少?最小生成树裸题,主要英语看的有点费劲。
解:kruskal+并查集优化

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e5+10;
int n,m,num,ww;
char ch,str;
int f[maxn];
int sum,count1;
typedef struct{
	int from,to,w;
}edges;
edges a[maxn];
bool cmp(edges a,edges b){
	return a.w<b.w;
}
int find_x(int x){
	if(x!=f[x]){
		f[x]=find_x(f[x]);
	}return f[x];
}
void skl(){
	int summax=0;
	memset(f,0,sizeof(f));
	for(int i=1;i<=n;i++)f[i]=i;
	int cnt=0;
	for(int i=1;i<=sum;i++){
		int c=find_x(a[i].from);
		int d=find_x(a[i].to);
		if(c!=d){
			cnt++;
			summax+=a[i].w;
			f[c]=d;
		}
		if(cnt==n-1){
			cout<<summax<<endl;
			break;
		}
	}
}
int main()
{
	while(cin>>n&&n){
		memset(a,0,sizeof(a));
		sum=0;count1=0;
		for(int i=1;i<=n-1;i++){
			cin>>ch;
			cin>>num;
			for(int i=1;i<=num;i++){
				cin>>str>>ww;
				a[++count1].from=ch-'A'+1;
				a[count1].to=str-'A'+1;
				a[count1].w=ww;
			}
			sum+=num;
		}
		sort(a+1,a+1+sum,cmp);
		/*for(int i=1;i<=sum;i++){ cout<<a[i].from<<"->"<<a[i].to<<" :"<<a[i].w<<endl; }*/
		skl();
	}
}

Networking

Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 21934 Accepted: 11148 Description

You are assigned to design network connections between certain points in a wide area. You are given a set of points in the area, and a set of possible routes for the cables that may connect pairs of points. For each possible route between two points, you are given the length of the cable that is needed to connect the points over that route. Note that there may exist many possible routes between two given points. It is assumed that the given possible routes connect (directly or indirectly) each two points in the area.
Your task is to design the network for the area, so that there is a connection (direct or indirect) between every two points (i.e., all the points are interconnected, but not necessarily by a direct cable), and that the total length of the used cable is minimal.
Input

The input file consists of a number of data sets. Each data set defines one required network. The first line of the set contains two integers: the first defines the number P of the given points, and the second the number R of given routes between the points. The following R lines define the given routes between the points, each giving three integer numbers: the first two numbers identify the points, and the third gives the length of the route. The numbers are separated with white spaces. A data set giving only one number P=0 denotes the end of the input. The data sets are separated with an empty line.
The maximal number of points is 50. The maximal length of a given route is 100. The number of possible routes is unlimited. The nodes are identified with integers between 1 and P (inclusive). The routes between two points i and j may be given as i j or as j i.
Output

For each data set, print one number on a separate line that gives the total length of the cable used for the entire designed network.
Sample Input

1 0

2 3
1 2 37
2 1 17
1 2 68

3 7
1 2 19
2 3 11
3 1 7
1 3 5
2 3 89
3 1 91
1 2 32

5 7
1 2 5
2 3 7
2 4 8
4 5 11
3 5 10
1 5 6
4 2 12

0
Sample Output

0
17
16
26

这个也是一个最小生成树裸题。。。。而且比上面那个还裸。。。。直接上代码了,把m=0的情况特判掉,基本上没甚问题了。

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=1e3+10;
typedef struct {
	int from,to,w;
}edges;
edges a[maxn];
int f[maxn];
int n,m;
bool cmp(edges a,edges b){
	return a.w<b.w;
}
int find_x(int x){
	if(x!=f[x]){
		f[x]=find_x(f[x]);
	}return f[x];
}
void skl(){
	int summax=0,cnt=0;
	for(int i=1;i<=n;i++)f[i]=i;
	for(int i=0;i<m;i++){
		int c=find_x(a[i].from);
		int d=find_x(a[i].to);
		if(c!=d){
			cnt++;
			summax+=a[i].w;
			f[c]=d;
		}
		if(cnt==n-1){
			cout<<summax<<endl;
			return;
		}
	}
	cout<<"0"<<endl;
}
int main()
{
	while(cin>>n&&n){
		memset(a,0,sizeof(a));
		cin>>m;
		if(m==0){cout<<"0"<<endl;continue;}
		for(int i=0;i<m;i++){
			cin>>a[i].from>>a[i].to>>a[i].w;
		}
		sort(a,a+m,cmp);
		skl();
	}
}

Building a Space Station

Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 15378 Accepted: 6770 Description

You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.

All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor’, or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.

You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.

You can ignore the width of a corridor. A corridor is built between points on two cells’ surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input

The input consists of multiple data sets. Each data set is given in the following format.

n
x1 y1 z1 r1
x2 y2 z2 r2

xn yn zn rn

The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.

The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.

Each of x, y, z and r is positive and is less than 100.0.

The end of the input is indicated by a line containing a zero.
Output

For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.

Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Sample Input

3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Sample Output

20.000
0.000
73.834

题目大意:你现在要给太空站写一个程序:让太空站 ,站与站之间连接起来(任意太空站),连接的费用是两个太空站之间的距离,太空站是一个球体,有可能会发生球体相交重叠的情况,这种情况连接的费用为0,问你将所有太空站连接起来最小费用是多少?
思路:在求两个站之间距离的时候把半径考虑进去,如果两个站距离<两个站半径之和,说明两个站有相交或者重合此时距离为0,否则就是两个站距离-两个站之间的半径,然后kruskal搞定了。(注意不能先对距离排序,然后求最小生成树的时候再去减掉两个半径,这个出来的不一定是最小生成树)
代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
const int maxn=105;
typedef struct {
	int from,to;
	double w;
}edges;
edges edge[maxn*maxn];
int f[maxn];
double a[maxn][4];
int countt=0;
int n;
bool cmp(edges a,edges b){
	return a.w<b.w;
}
int find_x(int x){
	if(x!=f[x]){
		f[x]=find_x(f[x]);
	}return f[x];
}
void skl(){
	double maxsum=0,cnt=0;
	for(int i=1;i<=n;i++)f[i]=i;
	for(int i=0;i<countt;i++){
		int a=find_x(edge[i].from);
		int b=find_x(edge[i].to);
		if(a!=b){
			maxsum+=edge[i].w;
			cnt++;
			f[a]=b;
		}
		/*if(cnt==n-1){讲道理这样也是可以的,但是poj有毒这样过不了 printf("%.3f\n",maxsum); return; }*/
	}
	printf("%.3f\n",maxsum);//这样才能过
}
int main()
{
	while(scanf("%d",&n)==1&&n){
		memset(a,0,sizeof(a));
		memset(edge,0,sizeof(edge));
		countt=0;
		for(int i=1;i<=n;i++){
			scanf("%lf%lf%lf%lf",&a[i][0],&a[i][1],&a[i][2],&a[i][3]);
		}
		for(int i=1;i<=n;i++){
			for(int j=i+1;j<=n;j++){
				edge[countt].from=i;
				edge[countt].to=j;
				edge[countt].w=((sqrt((a[i][0]-a[j][0])*(a[i][0]-a[j][0])+(a[i][1]-a[j][1])*(a[i][1]-a[j][1])+(a[i][2]-a[j][2])*(a[i][2]-a[j][2])))-a[i][3]-a[j][3])<0?0:((sqrt((a[i][0]-a[j][0])*(a[i][0]-a[j][0])+(a[i][1]-a[j][1])*(a[i][1]-a[j][1])+(a[i][2]-a[j][2])*(a[i][2]-a[j][2])))-a[i][3]-a[j][3]);
				countt++;
			}
		}
		sort(edge,edge+countt,cmp);
		skl();
	}
	return 0;
}

Constructing Roads

Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 31528 Accepted: 14081 Description

There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
Input

The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
Output

You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.
Sample Input

3
0 990 692
990 0 179
692 179 0
1
1 2
Sample Output

179

裸题

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=110;
int a[maxn][maxn];
int n,m;
int vis[maxn];
int dis[maxn];
void prime(int s){
	memset(vis,0,sizeof(vis));
	memset(dis,88,sizeof(dis));
	vis[s]=1;
	dis[s]=0;
	int maxsum=0;
	for(int i=1;i<=n;i++){
		dis[i]=min(dis[i],a[s][i]);
	}
	for(int q=1;q<=n-1;q++){
		int minn=inf,k;
		for(int i=1;i<=n;i++){
			if(!vis[i]&&dis[i]<minn){
				minn=dis[i];
				k=i;
			}
		}
		vis[k]=1;
		maxsum+=minn;
		for(int i=1;i<=n;i++){
			if(!vis[i]&&a[k][i]<dis[i])//注意这里不能省略成
			//dis[i]=min(dis[i],a[k][i]+dis[k])
			dis[i]=a[k][i];
		}
	}
	cout<<maxsum<<endl;
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		memset(a,88,sizeof(a));
		int x,y;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				scanf("%d",&a[i][j]);
			}
		}
		scanf("%d",&m);
		for(int i=1;i<=m;i++){
			scanf("%d%d",&x,&y);
			a[y][x]=a[x][y]=0;
		}
		prime(1);
	}	
	return 0;
}

QS Network

Time Limit: 2 Seconds Memory Limit: 65536 KB Sunny Cup 2003 - Preliminary Round April 20th, 12:00 - 17:00

Problem E: QS Network

In the planet w-503 of galaxy cgb, there is a kind of intelligent creature named QS. QScommunicate with each other via networks. If two QS want to get connected, they need to buy two network adapters (one for each QS) and a segment of network cable. Please be advised that ONE NETWORK ADAPTER CAN ONLY BE USED IN A SINGLE CONNECTION.(ie. if a QS want to setup four connections, it needs to buy four adapters). In the procedure of communication, a QS broadcasts its message to all the QS it is connected with, the group of QS who receive the message broadcast the message to all the QS they connected with, the procedure repeats until all the QS’s have received the message.

A sample is shown below:

A sample QS network, and QS A want to send a message.

Step 1. QS A sends message to QS B and QS C;

Step 2. QS B sends message to QS A ; QS C sends message to QS A and QS D;

Step 3. the procedure terminates because all the QS received the message.

Each QS has its favorate brand of network adapters and always buys the brand in all of its connections. Also the distance between QS vary. Given the price of each QS’s favorate brand of network adapters and the price of cable between each pair of QS, your task is to write a program to determine the minimum cost to setup a QS network.

Input

The 1st line of the input contains an integer t which indicates the number of data sets.

From the second line there are t data sets.

In a single data set,the 1st line contains an interger n which indicates the number of QS.

The 2nd line contains n integers, indicating the price of each QS’s favorate network adapter.

In the 3rd line to the n+2th line contain a matrix indicating the price of cable between ecah pair of QS.

Constrains:

all the integers in the input are non-negative and not more than 1000.

Output

for each data set,output the minimum cost in a line. NO extra empty lines needed.

Sample Input

1
3
10 20 30
0 100 200
100 0 300
200 300 0

Sample Output

370

题目大意:就是说在某个星球上有种叫做qs的生物,他们之间通过网络适配器和光缆传输,然后要你求将他们联通起来的最小值。
wa了一会,其实这个题和上面的那个球的半径是一样的做法,先把网络适配器和光缆一起考虑进去然后Kruskal解决。
代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1000100;
typedef struct {
	int from,to,w;
}edge;
edge edges[maxn];
int n;
int w[maxn];
int f[maxn];
int countt=0;
int find_x(int x){
	if(x!=f[x]){
		f[x]=find_x(f[x]);
	}return f[x];
} 
bool cmp(edge a,edge b){
	return a.w<b.w;
}
void skl(){
	int cnt=0,ans=0;
	for(int i=1;i<=n;i++)f[i]=i;
	for(int i=0;i<countt;i++){
		int a=find_x(edges[i].from);
		int b=find_x(edges[i].to);
		if(a!=b){
			f[a]=b;
			ans+=edges[i].w;
			cnt++;
		}
		if(cnt==n-1){
			break;
		}
	}
	cout<<ans<<endl;
}
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		memset(edges,0,sizeof(edges));
		memset(w,0,sizeof(w));
		memset(f,0,sizeof(f));
		scanf("%d",&n);
		countt=0;
		int laji;
		for(int i=1;i<=n;i++)scanf("%d",&w[i]);
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(i<j){
					edges[countt].from=i;
					edges[countt].to=j;
					scanf("%d",&edges[countt].w);
					edges[countt].w+=w[i]+w[j];
					countt++;
				}
				else scanf("%d",&laji);
			}
		}
		sort(edges,edges+countt,cmp);
		skl();
	}
}

Truck History

Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 37313 Accepted: 14304 Description

Advanced Cargo Movement, Ltd. uses trucks of different types. Some trucks are used for vegetable delivery, other for furniture, or for bricks. The company has its own code describing each type of a truck. The code is simply a string of exactly seven lowercase letters (each letter on each position has a very special meaning but that is unimportant for this task). At the beginning of company’s history, just a single truck type was used but later other types were derived from it, then from the new types another types were derived, and so on.

Today, ACM is rich enough to pay historians to study its history. One thing historians tried to find out is so called derivation plan – i.e. how the truck types were derived. They defined the distance of truck types as the number of positions with different letters in truck type codes. They also assumed that each truck type was derived from exactly one other truck type (except for the first truck type which was not derived from any other type). The quality of a derivation plan was then defined as
1/Σ(to,td)d(to,td)

where the sum goes over all pairs of types in the derivation plan such that to is the original type and td the type derived from it and d(to,td) is the distance of the types.
Since historians failed, you are to write a program to help them. Given the codes of truck types, your program should find the highest possible quality of a derivation plan.
Input

The input consists of several test cases. Each test case begins with a line containing the number of truck types, N, 2 <= N <= 2 000. Each of the following N lines of input contains one truck type code (a string of seven lowercase letters). You may assume that the codes uniquely describe the trucks, i.e., no two of these N lines are the same. The input is terminated with zero at the place of number of truck types.
Output

For each test case, your program should output the text “The highest possible quality is 1/Q.”, where 1/Q is the quality of the best derivation plan.
Sample Input

4
aaaaaaa
baaaaaa
abaaaaa
aabaaaa
0
Sample Output

The highest possible quality is 1/3.
题目大意:
给你n个长度为7的字符串,每个字符串与字符串之间的不同元素是他们之间的权值,给定字符串要你求最小值。
思路:prime Kruskal都行,(我错了一个很简单的地方,伤心~,string str[maxn];是一个char型二维数组,然后求不同元素时,我把它当一位数组去比了,导致wa。。。。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>

using namespace std;
const int maxn = 2010;
const int inf = 0x3f3f3f3f;

int vis[maxn];
int dis[maxn];
string str[maxn];
int a[maxn][maxn];
int n;

int check(int i, int j) {
	int ans = 0;
	for(int k=0;k<7;k++){
		if(str[i][k]!=str[j][k])ans++;
	}return ans;
}
int prime() {
	int ans = 0;
	memset(dis, 88, sizeof(dis));
	memset(vis, 0, sizeof(vis));
	vis[1] = 1; dis[1] = 0;
	for (int i = 1; i <= n; i++) {
		dis[i] = a[1][i];
	}
	for (int p = 1; p <= n - 1; p++) {
		int minn = inf, k;
		for (int i = 1; i <= n; i++) {
			if (!vis[i] && dis[i] < minn) {
				minn = dis[i];
				k = i;
			}
		}
		vis[k] = 1;
		ans += minn;
		for (int i = 1; i <= n; i++) {
			if (!vis[i] && dis[i] > a[k][i])
				dis[i] = a[k][i];
		}
	}
	return ans;
}
int main() {
	while (scanf("%d",&n)!=EOF&&n) {
		memset(a,0,sizeof(a));
		for (int i = 1; i <= n; i++)
		cin>>str[i];
		for (int i = 1; i <= n; i++) {
			for (int j = i+1 ; j <= n; j++) {
				int w=check(i,j);
				a[j][i]=a[i][j]=w;
			}
		}
		int cnt=prime();
		printf("The highest possible quality is 1/%d.\n", cnt);
	}
}

Highways

Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 25971 Accepted: 7606 Special Judge

Description

The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the most important towns. However, there are still some towns that you can’t reach via a highway. It is necessary to build more highways so that it will be possible to drive between any pair of towns without leaving the highway system.

Flatopian towns are numbered from 1 to N and town i has a position given by the Cartesian coordinates (xi, yi). Each highway connects exaclty two towns. All highways (both the original ones and the ones that are to be built) follow straight lines, and thus their length is equal to Cartesian distance between towns. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways.

The Flatopian government wants to minimize the cost of building new highways. However, they want to guarantee that every town is highway-reachable from every other town. Since Flatopia is so flat, the cost of a highway is always proportional to its length. Thus, the least expensive highway system will be the one that minimizes the total highways length.
Input

The input consists of two parts. The first part describes all towns in the country, and the second part describes all of the highways that have already been built.

The first line of the input file contains a single integer N (1 <= N <= 750), representing the number of towns. The next N lines each contain two integers, xi and yi separated by a space. These values give the coordinates of ith town (for i from 1 to N). Coordinates will have an absolute value no greater than 10000. Every town has a unique location.

The next line contains a single integer M (0 <= M <= 1000), representing the number of existing highways. The next M lines each contain a pair of integers separated by a space. These two integers give a pair of town numbers which are already connected by a highway. Each pair of towns is connected by at most one highway.
Output

Write to the output a single line for each new highway that should be built in order to connect all towns with minimal possible total length of new highways. Each highway should be presented by printing town numbers that this highway connects, separated by a space.

If no new highways need to be built (all towns are already connected), then the output file should be created but it should be empty.
Sample Input

9
1 5
0 0
3 2
4 5
5 1
0 4
5 2
1 2
5 3
3
1 3
9 7
1 2
Sample Output

1 6
3 7
4 9
5 7
8 3

题目大意:就是给你n个点给出他们的坐标,让你把所有点连起来并且费用最小,费用等于两点之间距离,然后有一些点已经连接了,让你输出剩下的要连接的点使得他们距离最小。
思路:先把题目给的点用并查集并起来,然后克鲁斯卡尔找最小生成树,因为村庄满足对称性,a->b,b->a,所有在输出的时候好像没有太严格(记得数组开大一点,wa了我又。。。。
代码:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stdio.h>
#include<math.h>
using namespace std;
const int maxn=1001000;
const int inf=0x3f3f3f3f;
typedef struct{
	int from,to;
	double w;
}edge;

int n,m,tt;
edge edges[maxn];
int a[10010],b[10010];
int f[10010];

bool cmp1(edge a,edge b){
	return a.w<b.w;
}
int find_x(int x){
	if(x!=f[x]){
		f[x]=find_x(f[x]); 
	}return f[x];
}

void skl(){
	int cnt=0;
	for(int i=1;i<=n;i++)f[i]=i;
	scanf("%d",&m);
	for(int i=0;i<m;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		int a=find_x(x);
		int b=find_x(y);
		if(a!=b){
			f[a]=b;
		}
	}
	tt=0;
	for(int i=1;i<=n;i++){
		for(int j=1+i;j<=n;j++){
			if(find_x(i)!=find_x(j)){
				edges[tt].from=i;
				edges[tt].to=j;
				edges[tt++].w=sqrt((double)(a[i]-a[j])*(a[i]-a[j])+(b[i]-b[j])*(b[i]-b[j]));
			}
		}
	}
	sort(edges,edges+tt,cmp1);
	for(int i=0;i<tt;i++){
		int a=find_x(edges[i].from);
		int b=find_x(edges[i].to);
		if(a!=b){
			cout<<edges[i].from<<" "<<edges[i].to<<endl;
			f[a]=b;
			cnt++;
		}
		if(cnt==n-1)break;
	}
}

int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d%d",&a[i],&b[i]);
	}
	skl();
}

Agri-Net
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 75265 Accepted: 31120
Description

Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input

The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output

For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output

28

题目大意:有个市长要给全村人装光纤,给出矩阵i到j人家的光纤费用为a[i][j],设计最小费用。
思路:最小生成树裸题了。
代码:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<stdio.h>
using namespace std;

const int maxn=105;
const int inf=0x3f3f3f3f;

int n;
int vis[maxn];
int dis[maxn];
int a[maxn][maxn];

void prime(int s){
	int ans=0;
	memset(vis,0,sizeof(vis));
	memset(dis,88,sizeof(dis));
	dis[s]=0;vis[s]=1;
	for(int i=1;i<=n;i++){
		dis[i]=min(dis[i],a[s][i]);
	}
	for(int p=1;p<=n-1;p++){
		int minn=inf,k;
		for(int i=1;i<=n;i++){
			if(!vis[i]&&dis[i]<minn){
				minn=dis[i];
				k=i;
			}
		}
		vis[k]=1;
		ans+=minn;
		for(int i=1;i<=n;i++){
			if(!vis[i]&&dis[i]>a[k][i]){
				dis[i]=a[k][i];
			}
		}
	}
	cout<<ans<<endl;
}
int main(){
	while(scanf("%d",&n)!=EOF){
		memset(a,0,sizeof(a));
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				scanf("%d",&a[i][j]);
			}
		}
		prime(1);
	}
} 

畅通工程再续
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 44951 Accepted Submission(s): 15144

Problem Description
相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现。现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全畅通!经过考察小组RPRush对百岛湖的情况充分了解后,决定在符合条件的小岛间建上桥,所谓符合条件,就是2个小岛之间的距离不能小于10米,也不能大于1000米。当然,为了节省资金,只要求实现任意2个小岛之间有路通即可。其中桥的价格为 100元/米。

Input
输入包括多组数据。输入首先包括一个整数T(T <= 200),代表有T组数据。
每组数据首先是一个整数C(C <= 100),代表小岛的个数,接下来是C组坐标,代表每个小岛的坐标,这些坐标都是 0 <= x, y <= 1000的整数。

Output
每组输入数据输出一行,代表建桥的最小花费,结果保留一位小数。如果无法实现工程以达到全部畅通,输出”oh!”.

Sample Input
2
2
10 10
20 20
3
1 1
2 2
1000 1000

Sample Output
1414.2
oh!
中文问题,题意不说了,思路:把两个点距离在10到1000的点存进来,然后Kruskal,最后判断一下边数是否等于n-1(树的基本性质),因为我们在存边的时候只存了距离在10到1000的点,那么如果有些点不满足这个条件势必不会存这条边,不存在这条边但是又要访问到所有点,就会出现边不会等于n-1的情况,这样我们用树的性质判断一下就好了。
坑点:单组输出,数据范围
代码:

#include<bits/stdc++.h>
using namespace std;

const int inf=0x3f3f3f3f;

int t,n,m;
int f[105];
double a[105],b[105];
typedef struct{
	int from,to;
	double w;
}edge;
edge edges[10010];
int cnt=0;

bool cmp(edge a,edge b){
	return a.w<b.w;
}
int find_x(int x){
	if(x!=f[x]){
		f[x]=find_x(f[x]);
	}return f[x];
}

void skl(){
	double ans=0.0;
	int tt=0;
	for(int i=1;i<=n;i++)f[i]=i;
	for(int i=0;i<cnt;i++){
		int a=find_x(edges[i].from);
		int b=find_x(edges[i].to);
		if(a!=b){
			ans+=edges[i].w;
			f[a]=b;
			tt++;
		}
		if(tt==n-1)break; 
	}
	if(tt==n-1)
		cout<<fixed<<setprecision(1)<<ans<<endl;
	else
	cout<<"oh!"<<endl;
}
int main(){
	cin>>t;
	while(t--){
		cin>>n;
		for(int i=1;i<=n;i++){
			cin>>a[i]>>b[i];
		}
		cnt=0;
		for(int i=1;i<=n;i++){
			for(int j=i+1;j<=n;j++){
				double t=(double)sqrt((a[i]-a[j])*(a[i]-a[j])+(b[i]-b[j])*(b[i]-b[j]));
				if(t>=10&&t<=1000){
					edges[cnt].from=i;
					edges[cnt].to=j;
					edges[cnt++].w=t*100;
				}
			}
		}
		sort(edges,edges+cnt,cmp);
		skl();
	}
	return 0;	
}

还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 70157 Accepted Submission(s): 31746

Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。

Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。

Output
对每个测试用例,在1行里输出最小的公路总长度。

Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0

Sample Output
3
5

Hint
Hint

Huge input, scanf is recommended.
水题。。。。

#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
const int inf=0x3f3f3f3f;
int vis[maxn];
int dis[maxn];
int a[maxn*10][maxn*10];
int n;
void prime(int s){
    int ans=0;
    memset(vis,0,sizeof(vis));
    memset(dis,88,sizeof(dis));
    dis[s]=0;vis[s]=1;
    for(int i=1;i<=n;i++){
        dis[i]=min(dis[i],a[s][i]);
    }
    for(int p=1;p<=n-1;p++){
        int minn=inf,k;
        for(int i=1;i<=n;i++){
            if(!vis[i]&&dis[i]<minn){
                minn=dis[i];
                k=i;
            }
        }
        vis[k]=1;
        ans+=minn;
        for(int i=1;i<=n;i++){
            if(!vis[i]&&dis[i]>a[k][i]){
                dis[i]=a[k][i];
            }
        }
    }
    printf("%d\n",ans);
}


int main(){
    int x,y,z;
    while(scanf("%d",&n)!=EOF&&n){
        memset(a,88,sizeof(a));
        for(int i=1;i<=(n*(n-1))/2;i++){
            scanf("%d%d%d",&x,&y,&z);
            if(a[x][y]>z)a[x][y]=a[y][x]=z; 
        }
        prime(1);
    }
} 

The Unique MST

Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 41441 Accepted: 15133

Description

Given a connected undirected graph, tell if its minimum spanning tree is unique.

Definition 1 (Spanning Tree): Consider a connected, undirected graph G = (V, E). A spanning tree of G is a subgraph of G, say T = (V’, E’), with the following properties:

  1. V’ = V.
  2. T is connected and acyclic.

Definition 2 (Minimum Spanning Tree): Consider an edge-weighted, connected, undirected graph G = (V, E). The minimum spanning tree T = (V, E’) of G is the spanning tree that has the smallest total cost. The total cost of T means the sum of the weights on all the edges in E’.
Input

The first line contains a single integer t (1 <= t <= 20), the number of test cases. Each case represents a graph. It begins with a line containing two integers n and m (1 <= n <= 100), the number of nodes and edges. Each of the following m lines contains a triple (xi, yi, wi), indicating that xi and yi are connected by an edge with weight = wi. For any two nodes, there is at most one edge connecting them.
Output

For each input, if the MST is unique, print the total cost of it, or otherwise print the string ‘Not Unique!’.
Sample Input

2
3 3
1 2 1
2 3 2
3 1 3
4 4
1 2 2
2 3 2
3 4 2
4 1 2
Sample Output

3
Not Unique!

题目大意:给n个顶点m条边要你判断是否会构成相同的最小生成树,如果构成输出 Not Unique!,否则输出最小生成树权。
思路:在第一次求最小生成树的时候把边记录下来,然后枚举把记录下来的边一一删去,加上除了这条边之外的其他权值次小的边,如果还能构成树而且权值和最小生成树一样说明有次小生成树。
(一开始是打算求完最小生成树之后,如果最小生成树最后一条边和次小生成树第一条边相同,说明可以输出Not Unique!,不知道为啥wa了。。。。好像没错哈。。。。
代码:

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

const int maxn=1e4+10;

typedef struct {
	int from,to,w;
}edge;
edge edges[maxn<<1];

int f[120];
int n,m,t,ans;
bool flag;
bool cmp(edge a,edge b){
	return a.w<b.w;
} 
int find_x(int x){
	if(x!=f[x]){
		f[x]=find_x(f[x]);
	}return f[x];
}

void skl(){
	int youdu[120];
	ans=0;
	int cnt=0;
	for(int i=1;i<=n;i++)f[i]=i;
	for(int i=1;i<=m;i++){
		int a=find_x(edges[i].from);
		int b=find_x(edges[i].to);
		if(a!=b){
			f[a]=b;
			youdu[cnt++]=i;
			ans+=edges[i].w;
		}
		if(cnt==n-1)break;
	}
	for(int q=0;q<cnt;q++){
		int summax=0,ttt=0;//每次要置零 
		for(int i=1;i<=n;i++)f[i]=i;
		for(int j=1;j<=m;j++){
			if(j==youdu[q])
			continue;
			int a=find_x(edges[j].from);
			int b=find_x(edges[j].to);
			if(a!=b){
				f[a]=b;
				summax+=edges[j].w;
				ttt++;
		    }
		}
		if(ttt==n-1&&summax==ans){
				flag=0;
				return;
		} 
	}
}
int main(){
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		for(int i=1;i<=m;i++){
			scanf("%d%d%d",&edges[i].from,&edges[i].to,&edges[i].w);
		}
		flag=true;
		sort(edges+1,edges+m+1,cmp);
		skl();
		if(flag){
			cout<<ans<<endl;
		}else{
			cout<<"Not Unique!"<<endl;
		}
	}
	return 0;
}