Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<cstdio>
- #include<vector>
- #include<bitset>
- using namespace std;
- int i,j,n,m,k,nr,tata[256],total;
- short int cost[256][256],h[256],cat[256],ajung[256],st[456],dr[456],f[256],unde[256];
- vector<int> a[256];
- bitset<256> fol;
- void upheap(int poz)
- {
- int tata=poz/2;
- if(tata>0&&cat[h[tata]]>cat[h[poz]])
- {
- int aux=unde[h[tata]];
- unde[h[tata]]=unde[h[poz]];
- unde[h[poz]]=aux;
- aux=h[tata];
- h[tata]=h[poz];
- h[poz]=aux;
- poz=tata;
- tata=poz/2;
- }
- }
- int min(int x,int y)
- {
- if(cat[h[x]]<cat[h[y]]) return x;
- return y;
- }
- void downheap(int poz)
- {
- int s=poz/2,d=poz/2+1;
- while(cat[h[s]]<cat[h[poz]]||cat[h[d]]<cat[h[poz]])
- {
- int fiu=min(s,d);
- int aux=unde[h[fiu]];
- unde[h[fiu]]=unde[h[poz]];
- unde[h[poz]]=aux;
- aux=h[fiu];
- h[fiu]=h[poz];
- h[poz]=aux;
- poz=fiu;
- s=poz/2;
- d=poz/2+1;
- }
- }
- int main()
- {
- freopen("online.in","r",stdin);
- freopen("online.out","w",stdout);
- scanf("%d%d",&n,&m);
- for(i=1;i<=m;++i)
- {
- int x,y,co;
- scanf("%d%d%d",&x,&y,&co);
- cost[x][y]=cost[y][x]=co;
- a[x].push_back(y);
- a[y].push_back(x);
- }
- h[1]=1;
- unde[1]=1;
- ++nr;
- cat[0]=30000;
- while(nr)
- {
- int u=h[1];
- total+=cat[u];
- tata[u]=ajung[u];
- fol[u]=1;
- unde[u]=0;
- h[1]=h[nr];
- unde[h[nr]]=1;
- h[nr]=0;
- --nr;
- downheap(1);
- for(i=0;i<a[u].size();++i)
- if(!fol[a[u][i]])
- {
- int fiu=a[u][i];
- if(unde[fiu])
- {
- if(cost[u][fiu]<cat[fiu])
- {
- cat[fiu]=cost[u][fiu];
- ajung[fiu]=u;
- upheap(unde[fiu]);
- }
- }
- else
- {
- h[++nr]=fiu;
- unde[fiu]=nr;
- cat[fiu]=cost[u][fiu];
- ajung[fiu]=u;
- upheap(nr);
- }
- }
- }
- printf("%d\n",total);
- scanf("%d",&k);
- for(i=1;i<=k;++i)
- {
- st[0]=0;
- dr[0]=0;
- int x,y,co;
- scanf("%d%d%d",&x,&y,&co);
- if((x==tata[y]||y==tata[x])&&co<cost[x][y])
- {
- total-=cost[x][y];
- total+=co;
- cost[x][y]=cost[y][x]=co;
- printf("%d\n",total);
- continue;
- }
- int s=x,d=y,p=0,q=0,cmax=0,ok=1,com=0;
- while(s>0)
- {
- f[s]=i;
- s=tata[s];
- }
- while(d>0)
- {
- int tat=tata[d];
- dr[++dr[0]]=d;
- if(f[d]==i)
- {
- com=d;
- break;
- }
- if(cost[d][tat]>cmax)
- {
- cmax=cost[d][tat];
- p=d;
- q=tat;
- ok=0;
- }
- d=tat;
- }
- s=x;
- while(s!=com)
- {
- int tat=tata[s];
- st[++st[0]]=s;
- if(cost[s][tat]>cmax)
- {
- cmax=cost[s][tat];
- p=s;
- q=tat;
- ok=1;
- }
- s=tat;
- }
- if(co<cmax)
- {
- if(ok)
- {
- j=st[0];
- while(st[j]!=p) --j;
- for(;j>1;--j) tata[st[j]]=st[j-1];
- tata[st[1]]=y;
- total-=cmax;
- total+=co;
- cost[x][y]=cost[y][x]=co;
- printf("%d\n",total);
- }
- else
- {
- j=dr[0];
- while(dr[j]!=p) --j;
- for(;j>1;--j) tata[dr[j]]=dr[j-1];
- tata[dr[1]]=x;
- total-=cmax;
- total+=co;
- cost[x][y]=cost[y][x]=co;
- printf("%d\n",total);
- }
- }
- else printf("%d\n",total);
- }
- fclose(stdin);
- fclose(stdout);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement