Cod sursa(job #466192)

Utilizator sodamngoodSo Damn Good sodamngood Data 26 iunie 2010 12:05:04
Problema Colorare3 Scor 50
Compilator cpp Status done
Runda Stelele Informaticii 2010, gimnaziu si clasa a IX-a, Ziua 2 Marime 2.49 kb
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define nmax 100010
#define mod 1000000007
#define maxbuf 65536
#define LL long long
#define PB push_back

char buff[maxbuf];
int N, K, viz[nmax], deg[nmax];
long long fact[nmax];
long long sol;
vector<int> G[nmax];

void preproc() {
    fact[0] = 1;
    fact[1] = (K - 1) % mod;
    for(int i=2; i<=N; i++) {
         fact[i] = (LL)fact[i-1]*(K - i);
         while(fact[i] >= mod) fact[i] -= mod;
    }
}

void DetArbore(int nod) {
     int p, q;
     queue<int> Q;
     vector<int> X;
     viz[nod]=1;
     Q.push(nod);
     while(!Q.empty()) {
          p=Q.front(); Q.pop();
          for(vector<int>::iterator it=G[p].begin(); it!=G[p].end(); it++) {
              if(!viz[(*it)]) {
                   viz[(*it)]=1;
                   X.push_back(*it);
                   Q.push((*it));
              }
          }
          deg[p] = X.size();
          X.clear();
     }
}

int main() {
    FILE *f1=fopen("colorare3.in", "r"), *f2=fopen("colorare3.out", "w");
    int i, x1 = 0, y1 = 0, p;
    
    fscanf(f1, "%d %d\n", &N, &K);
    
    preproc();
    
    /**
    for(i=1; i<N; i++) {
         fscanf(f1, "%d %d\n", &p, &q);
         G[p].PB(q);
         G[q].PB(p);
    }
    **/
    
    int laX = 1, laY = 0;
    while(!feof(f1)) {
         int len = fread(buff, 1, maxbuf, f1);
         if(len < maxbuf) buff[len] = 0;
         
         for(i=0; i<len; i++) {
              if(laY) {
                   if('0' <= buff[i] && buff[i] <= '9') {
                        y1 = y1*10 + buff[i] - '0';
                   }
                   else {
                        G[y1].PB(x1);
                        G[x1].PB(y1);
                        laX = 1; laY = 0;
                        x1 = y1 = 0;
                   }
              }
              else {
                   if('0' <= buff[i] && buff[i] <= '9') {
                        x1 = x1*10 + buff[i] - '0';
                   }
                   else {
                        laY = 1;
                   }
              } 
         }
    }
    
    DetArbore(1);
    
    sol = 1;
    p = deg[1];
    long long x = ((LL)fact[p-1] * K) % mod;
    sol = ((LL)sol*x) % mod;
    
    for(i=2; i<=N; i++) {
         if(deg[i]) {
              int p = deg[i];
              sol = ((LL)sol*fact[p]) % mod;
         }
    }

    fprintf(f2, "%lld\n", sol);
    fclose(f1); fclose(f2);
    return 0;
}