| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
是我的堆写的不好么,为啥TLE ╮(╯▽╰)╭ 大牛有空给说下哈~~~#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
const int MAX_NODE = 100+2;
const int maxint = 0x7fffffff;
struct Edge
{
int vertex;
int cost;
};
vector<Edge> Graph[MAX_NODE];
struct Record
{
int id;
int key;
};
int pos[MAX_NODE]; //!!!! positon in heap for node i
Record h[MAX_NODE];
int size;
void GoUp(int j)
{
int i;
Record x = h[j];
while ( j > 1)
{
i = j/2;
if (x.key >= h[i].key) break;
h[j]= h[i]; //i goes down
pos[h[i].id] = j;
j = i;
}
h[j] = x;
pos[x.id] = j;
}
void GoDown(int i)
{
int j;
Record x = h[i];
while (2*i <= size)
{
j = 2*i;
if (j < size && h[j].key > h[j+1].key) j++;
if (x.key <= h[j].key) break;
h[i] = h[j];
pos[h[j].id] = i;
}
h[i] = x;
pos[x.id] = i;
}
Record Pop()
{
Record re = h[1];
pos[re.id] = -1; //already coming out
h[1] = h[size];
pos[h[size].id] = 1;
size--;
GoDown(1);
return re;
}
void InitHeap(int n)
{
int i;
for (i=1; i<=n; i++)
{
h[i].id = i;
if (i == 1) h[1].key = 0;
else h[i].key = maxint;
pos[i] = i;
}
size = n;
}
int Prim(int n)
{
int ans = 0;
int i, j;
Record min;
InitHeap(n);
for (i=1; i<=n; i++)
{
min = Pop();
int v = min.id;
int c = min.key;
ans += c;
for (j=1; j<=Graph[i].size(); j++)
{
int u = Graph[v][j-1].vertex;
if (pos[u] != -1 && Graph[v][j-1].cost < h[pos[u]].key)
{
h[pos[u]].key = Graph[v][j-1].cost;
GoUp(pos[u]);
}
}
}
return ans;
}
int main(int argc, char *argv[])
{
int N, Q;
int i, j;
int c, u, v;
//freopen("test.txt", "r", stdin);
scanf("%d", &N);
Edge e;
for (i=1; i<=N; i++)
{
for (j=1; j<=N; j++)
{
scanf("%d", &c);
if (i == j) continue;
e.vertex = j;
e.cost = c;
Graph[i].push_back(e);
e.vertex = i;
Graph[j].push_back(e);
}
}
scanf("%d", &Q);
for (i=1; i<=Q; i++)
{
scanf("%d %d", &u, &v);
for (j=1; j<=Graph[u].size(); j++)
{
if (Graph[u][j-1].vertex == v)
Graph[u][j-1].cost = 0;
}
for (j=1; j<=Graph[v].size(); j++)
{
if (Graph[v][j-1].vertex == u)
Graph[v][j-1].cost = 0;
}
}
int ans = 0;
ans = Prim(N);
printf("%d\n", ans);
// system("PAUSE");
return EXIT_SUCCESS;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator