Cod sursă (job #271764)

Utilizator avatar VladAfrasinei Vlad Afrasinei VladAfrasinei IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp | 2.29 kb
Rundă Arhiva de probleme Status evaluat
Dată 26 ian. 2017 11:37:16 Scor 70
#include <algorithm>
#include <cctype>
#include <cstdio>
#define BUF_SIZE 100000
using namespace std;
FILE *f=fopen("zapada.in","r");
FILE *g=fopen("zapada.out","w");
int n,m,k;
struct muchie
{
    int x,y,z;
};
muchie a[101005],b[101005];
int t[10105],h[10105],c,nr;
char buf[BUF_SIZE];
int pos = BUF_SIZE;

inline char getChar(FILE *f) {
  if (pos == BUF_SIZE) {
    fread(buf, 1, BUF_SIZE, f);
    pos = 0;
  }
  return buf[pos++];
}

inline int readInt(FILE *f) {
  int result = 0;
  char c;
  do {
    c = getChar(f);
  } while (!isdigit(c));

  do {
    result = 10 * result + c - '0';
    c = getChar(f);
  } while (isdigit(c));

  return result;
}
inline int Find(int x)
{
    while(t[x]!=0)
        x=t[x];
    return x;
}
inline void Union(unsigned short int x,unsigned short int y)
{
    if(h[x]>h[y])
        t[y]=x;
    else
    {
        t[x]=y;
        if(h[x]==h[y])
            h[y]++;
    }
}
inline bool cmp(muchie l1,muchie l2)
{
    if(l1.z<l2.z)
        return 1;
    return 0;
}
int main()
{
    int i,nrmsel,v1,v2,x1,x2,s=0,j;
n=readInt(f);
m=readInt(f);
k=readInt(f);
for(i=1;i<=m;i++)
{
    a[i].x=readInt(f);
    a[i].y=readInt(f);
    a[i].z=readInt(f);
}
sort(a+1,a+m+1,cmp);
for(i=1;i<=n;i++)
        h[i]=1;
nrmsel=0;
i=1;
while(nrmsel<n-1||i<=m)
{
    v1=a[i].x;
    v2=a[i].y;
    x1=Find(v1);
    x2=Find(v2);
    if(x1!=x2)
    {
        nrmsel++;
        b[nrmsel].x=a[i].x;
        b[nrmsel].y=a[i].y;
        b[nrmsel].z=a[i].z;
        s=s+a[i].z;
        Union(x1,x2);
    }
    i++;
}
nr=nrmsel;
for(i=1;i<=nr;i++)
    a[i]=b[i];
fprintf(g,"%d\n",s);
for(i=1;i<=k;i++)
{   s=0;
    nr++;
    a[nr].x=readInt(f);
    a[nr].y=readInt(f);
    a[nr].z=readInt(f);
    for(j=1;j<=n;j++)
    {
        t[j]=0;
        h[j]=1;
    }
    sort(a+1,a+nr+1,cmp);
    nrmsel=0;
    j=1;
    while(nrmsel<n-1||j<=nr)
    {
    v1=a[j].x;
    v2=a[j].y;
    x1=Find(v1);
    x2=Find(v2);
    if(x1!=x2)
    {
        nrmsel++;
        b[nrmsel].x=a[j].x;
        b[nrmsel].y=a[j].y;
        b[nrmsel].z=a[j].z;
        s=s+a[j].z;
        Union(x1,x2);
    }
    j++;
    }
    for(j=1;j<=nrmsel;j++)
        a[j]=b[j];
    nr=nrmsel;
    fprintf(g,"%d\n",s);
}
    return 0;
}