dijkstra+heap

来源:互联网 发布:ubuntu用u盘安装 编辑:程序博客网 时间:2024/05/29 12:18

手写堆

#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>using namespace std;int n,p,c,num;const int maxn = 2000;const int maxm = 3000;int tot,head[maxn],pos[maxn],cnt;int ans = (1<<30);struct node{    int v,w,next;}edges[maxm];void add(int u,int v,int w){    edges[tot].v = u;edges[tot].w = w;edges[tot].next = head[v];head[v] = tot++;    edges[tot].v = v;edges[tot].w = w;edges[tot].next = head[u];head[u] = tot++;}void init(){    memset(head,-1,sizeof(head));    scanf("%d%d%d",&n,&p,&c);    for(int i = 1 ; i <= n ; i++){        scanf("%d",&pos[i]);    }    for(int j = 0 ; j < c; j++){        int u,v,w;        scanf("%d%d%d",&u,&v,&w);        add(u,v,w);    }}struct np{    int pp;    int ww;}heap[maxm];int index[maxn];void up_heap(int no,int dis){    int tmp = index[no];    while((tmp>>1) >= 1 && dis < heap[tmp>>1].ww){        heap[tmp].ww = heap[tmp>>1].ww;        heap[tmp].pp = heap[tmp>>1].pp;        index[heap[tmp>>1].pp] = tmp;        tmp >>= 1;    }    heap[tmp].ww = dis;    heap[tmp].pp = no;    index[no] = tmp;}void down_heap(int no,int dis){    int tmp = index[no];    while((tmp << 1) < cnt &&(dis > heap[tmp<<1].ww || dis > heap[tmp<<1|1].ww )){        int k = heap[tmp<<1].ww > heap[tmp <<1 |1].ww ? tmp*2+1:tmp*2;        heap[tmp].ww = heap[k].ww;        heap[tmp].pp = heap[k].pp;        index[heap[k].pp] = tmp;        tmp = k;    }    heap[tmp].ww = dis;    heap[tmp].pp = no;    index[no] = tmp;}void swap_heap(int i,int j){    index[heap[i].pp ] = j;    index[heap[j].pp ] = i;    swap(heap[i],heap[j]);}void dijkstra(int ct){    cnt = 1;    for(int i = 1; i <= p +1 ; i++){        if(i == ct) continue;        //cout <<"i = "<<i<<endl;        heap[cnt].pp = i;        heap[cnt].ww = (1<<30);        index[i] = cnt++;    }    heap[cnt].pp = ct;    heap[cnt].ww = 0;    index[ct] = cnt;    cnt = p-1;    for(int i = 1; i <= p ; i++){        for(int k = head[ct] ; k != -1; k = edges[k].next){            int v = edges[k].v;//cout << heap[index[5]].ww <<"   "<<heap[index[1]].ww<<endl;            if(index[v] < p && heap[index[v]].ww > heap[index[ct]].ww+edges[k].w){                //删除这个,加入新权值               // printf("v = %d  pre [%d[ = %d\n",v,ct,heap[index[ct]].ww+edges[k].w);                up_heap(v,heap[index[ct]].ww+edges[k].w);            }        }        ct = heap[1].pp;        swap_heap(1,cnt);        swap_heap(cnt,cnt+1);        --cnt;        down_heap(heap[1].pp,heap[1].ww);    }}void sov(){    for(int i = 1 ; i <= p ; i++){        dijkstra(i);        int sum = 0;        for(int j  = 1; j <= n ; j++){            if(pos[j] == i) continue;            sum += heap[index[pos[j]]].ww;            //printf("sm[%d] = %d\n",pos[j],heap[index[pos[j]]].ww);        }       // cout <<sum<<endl;        ans = min(ans,sum);    }    printf("%d\n",ans);}int main(){    init();    sov();}
0 0
原创粉丝点击