poj 2891 Strange Way to Express Integers 2012-09-05

http://poj.org/problem?id=2891 

 

解线性模方程组。

比较坑爹,数据比较大,很容易溢出。

 

  1 Program poj2891;
  2 
  3 var m:int64;
  4 
  5     a,r:array[1..30000000]of int64;
  6 
  7     ans,x,y,lcm:int64;
  8 
  9 
 10  Procedure init;
 11 
 12  var i,j:longint;
 13 
 14   begin
 15 
 16        m:=0;
 17 
 18        readln(m);
 19 
 20        for i:=1 to m do
 21 
 22          readln(a[i],r[i]);
 23 
 24   end;
 25 
 26 
 27  Function extended_gcd(a,b:int64;var x,y:int64):int64;
 28 
 29  var k:int64;
 30 
 31   begin
 32 
 33       if b=0 then begin
 34 
 35                      extended_gcd:=a;
 36 
 37                      x:=1;y:=0;
 38 
 39                   end
 40 
 41              else begin
 42 
 43                      extended_gcd:=extended_gcd(b,a mod b,x,y);
 44 
 45                      k:=x;x:=y;y:=k-(a div b)*y;
 46 
 47                   end;
 48 
 49   end;
 50 
 51 
 52  Procedure print(ans:int64);
 53 
 54   begin
 55 
 56      writeln(ans);
 57 
 58   end;
 59 
 60 
 61  Procedure main;
 62 
 63  var i:longint;
 64 
 65      d,ai,ri,k:int64;
 66 
 67   begin
 68 
 69      ans:=0;
 70 
 71      ai:=a[1];ri:=r[1];
 72 
 73      for i:=2 to m do
 74 
 75       begin
 76 
 77           d:=extended_gcd(ai,a[i],x,y);
 78 
 79           lcm:=a[i]*ai div d;
 80 
 81           if (r[i]-ri)mod d<>0 then begin print(-1);exit;end;
 82 
 83           k:=((x mod a[i])*(r[i]-ri) mod a[i])div d;  //这个取余很重要,没有的话就会溢出,在这wa了好久
 84 
 85           ri:=((ri+ai*k) mod lcm+lcm)mod lcm;
 86 
 87           ai:=lcm;
 88 
 89       end;
 90 
 91      print(ri);
 92 
 93   end;
 94 
 95 
 96 Begin
 97 
 98     assign(input,'input.in');reset(input);
 99 
100     assign(output,'output.out');rewrite(output);
101 
102          while not(eof) do
103 
104           begin
105 
106              init;
107 
108              if m<>0 then main;
109 
110           end;
111 
112     close(Input);close(Output);
113 
114 end.

 

posted on 2016-03-02 20:56  Yesphet  阅读(118)  评论(0编辑  收藏  举报