Question: Give N, which represents N towns.
In the next N rows, each line has a coordinate (x, y) representing the coordinate of the nth town.
Let's look at another M, which indicates that several roads have been repaired. In the next M rows, two numbers (I, j) in each row indicate that the I and j towns have roads.
Ask the minimum number of roads you need to build and output the two towns connected to each road.
Because it is spj, there is no order for output. Www.2cto.com
At first glance, I knew it was a pure MST, and I did it easily. I handed in about 20 times, and all kinds of TLE finally got ~~ Then I tried again 10 times and found an amazing thing...
[Cpp]
# Include <iostream>
# Include <cstdio>
# Include <algorithm>
# Include <string>
# Include <cmath>
# Include <cstring>
# Include <queue>
# Include <set>
# Include <stack>
# Include <map>
# Deprecision Max 20005
Struct node
{
Int x, y;
Double len;
} Line [570000];
Struct node1
{
Int x, y;
} Road [1, 800];
Bool cmp (node & x, node & y) // pay attention to this
{
Return x. len <y. len;
}
Int f [570000];
Int find (int x)
{
If (f [x] = x)
Return x;
Else
Return f [x] = find (f [x]);
}
Double getdis (node1 & x, node1 & y) // and this ..
{
Return sqrt (double) (x. x-y.x) * (x. x-y.x) + (double) (x. y-y.y) * (x. y-y.y ));
}
Void merge (int x, int y)
{
X = find (x );
Y = find (y );
F [y] = x;
}
Using namespace std;
Int main ()
{
Int I, j, l, n, m;
Int x, y, s;
Int q;
Cin> n;
Node1 test;
Int k = 0;
Int sum = 0;
For (I = 1; I <= n; I ++)
{
Scanf ("% d", & road [I]. x, & road [I]. y );
}
Cin> q;
For (I = 0; I <= 570000; I ++)
F [I] = I;
For (I = 0; I <q; I ++)
{
Scanf ("% d", & x, & y );
Merge (x, y );
}
For (I = 1; I <= n; I ++)
{
For (j = I + 1; j <= n; j ++)
{
If (find (I )! = Find (j ))
{
Line [k]. x = I;
Line [k]. y = j;
Line [k]. len = getdis (road [I], road [j]);
K ++;
}
}
}
Int num = 0;
Sort (line, line + k, cmp );
For (I = 0; I <k; I ++)
{
Int a = find (line [I]. x );
Int B = find (line [I]. y );
If (! = B)
{
F [B] =;
Num ++;
Printf ("% d \ n", line [I]. x, line [I]. y );
}
If (num> = N-1) break;
}
Return 0;
}
[Cpp]
I must have seen the two places where I wrote comments... In the beginning, the sorting I wrote was
Bool cmp (node x, node y)
{
Return x. len <y. len;
}
The following function is not added &.
Then it's TLE .. I have changed the main program for at least 10 times. Or TLE.
It suddenly occurred that the function of sorting and Calculating distance was the most time-consuming. So we changed these two points .. I did not expect.
1751 Accepted 6860 K 1000 ms c ++ 1674B // not added
1751 Accepted 6856 K 641 ms c ++ 1678B // added
It is 600 MS. However, the problem is fully explained.
Of course, this is still a lot of time .. Continue optimization ..
Finally, make the questions more careful!
Author: kdqzzxxcc