text
stringlengths
59
71.4k
`timescale 1ns/10ps module jaxa_pll_0( // interface 'refclk' input wire refclk, // interface 'reset' input wire rst, // interface 'outclk0' output wire outclk_0, // interface 'locked' output wire locked ); altera_pll #( .fractional_vco_multiplier("false"), .reference_clock_frequency("100.0 MHz"), .operation_mode("direct"), .number_of_clocks(1), .output_clock_frequency0("100.000000 MHz"), .phase_shift0("0 ps"), .duty_cycle0(50), .output_clock_frequency1("0 MHz"), .phase_shift1("0 ps"), .duty_cycle1(50), .output_clock_frequency2("0 MHz"), .phase_shift2("0 ps"), .duty_cycle2(50), .output_clock_frequency3("0 MHz"), .phase_shift3("0 ps"), .duty_cycle3(50), .output_clock_frequency4("0 MHz"), .phase_shift4("0 ps"), .duty_cycle4(50), .output_clock_frequency5("0 MHz"), .phase_shift5("0 ps"), .duty_cycle5(50), .output_clock_frequency6("0 MHz"), .phase_shift6("0 ps"), .duty_cycle6(50), .output_clock_frequency7("0 MHz"), .phase_shift7("0 ps"), .duty_cycle7(50), .output_clock_frequency8("0 MHz"), .phase_shift8("0 ps"), .duty_cycle8(50), .output_clock_frequency9("0 MHz"), .phase_shift9("0 ps"), .duty_cycle9(50), .output_clock_frequency10("0 MHz"), .phase_shift10("0 ps"), .duty_cycle10(50), .output_clock_frequency11("0 MHz"), .phase_shift11("0 ps"), .duty_cycle11(50), .output_clock_frequency12("0 MHz"), .phase_shift12("0 ps"), .duty_cycle12(50), .output_clock_frequency13("0 MHz"), .phase_shift13("0 ps"), .duty_cycle13(50), .output_clock_frequency14("0 MHz"), .phase_shift14("0 ps"), .duty_cycle14(50), .output_clock_frequency15("0 MHz"), .phase_shift15("0 ps"), .duty_cycle15(50), .output_clock_frequency16("0 MHz"), .phase_shift16("0 ps"), .duty_cycle16(50), .output_clock_frequency17("0 MHz"), .phase_shift17("0 ps"), .duty_cycle17(50), .pll_type("General"), .pll_subtype("General") ) altera_pll_i ( .rst (rst), .outclk ({outclk_0}), .locked (locked), .fboutclk ( ), .fbclk (1'b0), .refclk (refclk) ); endmodule
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HD__A211OI_BEHAVIORAL_V `define SKY130_FD_SC_HD__A211OI_BEHAVIORAL_V /** * a211oi: 2-input AND into first input of 3-input NOR. * * Y = !((A1 & A2) | B1 | C1) * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none `celldefine module sky130_fd_sc_hd__a211oi ( Y , A1, A2, B1, C1 ); // Module ports output Y ; input A1; input A2; input B1; input C1; // Module supplies supply1 VPWR; supply0 VGND; supply1 VPB ; supply0 VNB ; // Local signals wire and0_out ; wire nor0_out_Y; // Name Output Other arguments and and0 (and0_out , A1, A2 ); nor nor0 (nor0_out_Y, and0_out, B1, C1); buf buf0 (Y , nor0_out_Y ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_HD__A211OI_BEHAVIORAL_V
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; int a[n][m]; int b[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) cin >> a[i][j]; } for (int i = 0; i < n; i++) { b[i] = a[i][0]; for (int j = 1; j < m; j++) b[i] = min(a[i][j], b[i]); } int ans = b[0]; for (int i = 1; i < n; i++) { ans = max(b[i], ans); } cout << ans; }
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { vector<int> v; int n; cin >> n; for (int i = 0; i < n; i++) { int t; cin >> t; v.push_back(t); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); v.erase(remove(v.begin(), v.end(), 0), v.end()); cout << v.size() << n ; }
// file: Clock35MHz_exdes.v // // (c) Copyright 2008 - 2011 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // //---------------------------------------------------------------------------- // Clocking wizard example design //---------------------------------------------------------------------------- // This example design instantiates the created clocking network, where each // output clock drives a counter. The high bit of each counter is ported. //---------------------------------------------------------------------------- `timescale 1ps/1ps module Clock35MHz_exdes #( parameter TCQ = 100 ) (// Clock in ports input CLK_IN1, // Reset that only drives logic in example design input COUNTER_RESET, output [1:1] CLK_OUT, // High bits of counters driven by clocks output COUNT, // Status and control signals output LOCKED ); // Parameters for the counters //------------------------------- // Counter width localparam C_W = 16; // When the clock goes out of lock, reset the counters wire reset_int = !LOCKED || COUNTER_RESET; reg rst_sync; reg rst_sync_int; reg rst_sync_int1; reg rst_sync_int2; // Declare the clocks and counter wire clk_int; wire clk_n; wire clk; reg [C_W-1:0] counter; // Instantiation of the clocking network //-------------------------------------- Clock35MHz clknetwork (// Clock in ports .CLK_IN1 (CLK_IN1), // Clock out ports .CLK_OUT1 (clk_int), // Status and control signals .LOCKED (LOCKED)); assign clk_n = ~clk; ODDR2 clkout_oddr (.Q (CLK_OUT[1]), .C0 (clk), .C1 (clk_n), .CE (1'b1), .D0 (1'b1), .D1 (1'b0), .R (1'b0), .S (1'b0)); // Connect the output clocks to the design //----------------------------------------- assign clk = clk_int; // Reset synchronizer //----------------------------------- always @(posedge reset_int or posedge clk) begin if (reset_int) begin rst_sync <= 1'b1; rst_sync_int <= 1'b1; rst_sync_int1 <= 1'b1; rst_sync_int2 <= 1'b1; end else begin rst_sync <= 1'b0; rst_sync_int <= rst_sync; rst_sync_int1 <= rst_sync_int; rst_sync_int2 <= rst_sync_int1; end end // Output clock sampling //----------------------------------- always @(posedge clk or posedge rst_sync_int2) begin if (rst_sync_int2) begin counter <= #TCQ { C_W { 1'b 0 } }; end else begin counter <= #TCQ counter + 1'b 1; end end // alias the high bit to the output assign COUNT = counter[C_W-1]; endmodule
#include <bits/stdc++.h> using namespace std; const long long mod = 998244353; int n, m, k; int p[40]; struct query { int l, r, x; }; struct query q[500005]; int max0[500005], max1[500005]; long long dp[500005]; long long s[500005]; void solve() { cin >> n >> k >> m; p[0] = 1; for (int i = 1; i < 40; i++) p[i] = (p[i - 1] << 1); n++; for (int(i) = (1); (i) <= (m); ++(i)) cin >> q[i].l >> q[i].r >> q[i].x; m++; q[m].l = n; q[m].r = n; q[m].x = 0; long long ans = 1; for (int(j) = (0); (j) <= (k - 1); ++(j)) { for (int(i) = (0); (i) <= (n); ++(i)) { max0[i] = max1[i] = -1; } for (int(i) = (1); (i) <= (m); ++(i)) { if (q[i].x & p[j]) { if (max1[q[i].l] < q[i].r) max1[q[i].l] = q[i].r; } else { if (max0[q[i].r] < q[i].l) max0[q[i].r] = q[i].l; } } for (int i = 0; i <= n; i++) s[i] = 0; int L0 = 0; int R1 = -1; dp[0] = 1; s[0] = 1; for (int i = 1; i <= n; i++) { R1 = max(R1, max1[i]); if (i <= R1) { dp[i] = 0; } else { dp[i] = (L0 == 0 ? s[i - 1] : s[i - 1] - s[L0 - 1]); dp[i] %= mod; } s[i] = (s[i - 1] + dp[i]) % mod; L0 = max(L0, max0[i]); } ans = (ans * dp[n]) % mod; } if (ans < 0) ans += mod; cout << (ans) << n ; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T = 1; for (int t = 1; t <= T; t++) solve(); }
#include <bits/stdc++.h> using namespace std; double dpsm[200001][26] = {0}; double dpfm[200001][26] = {0}; double ans = 0; int main() { int n; cin >> n; string s, f; cin >> s >> f; dpsm[0][s[0] - A ] = 1; dpfm[0][f[0] - A ] = 1; for (int i = 0; i < 26; ++i) { char c = A + i; for (int j = 1; j < s.size(); ++j) { if (s[j] == c) { dpsm[j][i] = (dpsm[j - 1][i] + j + 1); } else { dpsm[j][i] = dpsm[j - 1][i]; } if (f[j] == c) { dpfm[j][i] = dpfm[j - 1][i] + j + 1; } else { dpfm[j][i] = dpfm[j - 1][i]; } } } double r = (1.0 * (n) * (n + 1) * (2 * n + 1)) / 6.0; for (int j = 0; j < s.size(); ++j) { ans += 1.0 * (s.size() - j) * dpfm[j][s[j] - A ] / r; } for (int j = 0; j < f.size(); ++j) { if (f[j] == s[j]) { ans += 1.0 * (s.size() - j) * (dpsm[j][f[j] - A ] - j - 1) / r; } else { ans += 1.0 * (s.size() - j) * dpsm[j][f[j] - A ] / r; } } printf( %.9f n , ans); return 0; }
// Copyright 2020-2022 F4PGA Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 module conflict_dsp_clk ( input wire CLK_A, input wire CLK_B, input wire [ 8:0] A, input wire [ 8:0] B, output wire [17:0] Z ); reg [8:0] ra; always @(posedge CLK_A) ra <= A; reg [8:0] rb; always @(posedge CLK_B) rb <= B; MULT9X9 # ( .REGINPUTA("BYPASS"), .REGINPUTB("BYPASS"), .REGOUTPUT("BYPASS") ) mult ( .A (ra), .B (rb), .Z (Z) ); endmodule module conflict_ff_clk ( input wire CLK1, input wire CLK2, input wire [ 8:0] A, input wire [ 8:0] B, output wire [17:0] Z ); reg [17:0] z; always @(posedge CLK1) Z[17:9] <= z[17:9]; always @(posedge CLK2) Z[ 8:0] <= z[ 8:0]; MULT9X9 # ( .REGINPUTA("BYPASS"), .REGINPUTB("BYPASS"), .REGOUTPUT("BYPASS") ) mult ( .A (A), .B (B), .Z (z) ); endmodule module conflict_ff_rst ( input wire CLK, input wire RST1, input wire RST2, input wire [ 8:0] A, input wire [ 8:0] B, output wire [17:0] Z ); reg [17:0] z; always @(posedge CLK or posedge RST1) if (RST1) Z[17:9] <= 0; else Z[17:9] <= z[17:9]; always @(posedge CLK or posedge RST2) if (RST2) Z[ 8:0] <= 0; else Z[ 8:0] <= z[ 8:0]; MULT9X9 # ( .REGINPUTA("BYPASS"), .REGINPUTB("BYPASS"), .REGOUTPUT("BYPASS") ) mult ( .A (A), .B (B), .Z (z) ); endmodule module conflict_ff_ena ( input wire CLK, input wire ENA1, input wire ENA2, input wire [ 8:0] A, input wire [ 8:0] B, output wire [17:0] Z ); reg [17:0] z; always @(posedge CLK) if (ENA1) Z[17:9] <= z[17:9]; always @(posedge CLK) if (ENA2) Z[ 8:0] <= z[ 8:0]; MULT9X9 # ( .REGINPUTA("BYPASS"), .REGINPUTB("BYPASS"), .REGOUTPUT("BYPASS") ) mult ( .A (A), .B (B), .Z (z) ); endmodule module conflict_dsp_port ( input wire CLK_A, input wire [ 8:0] A, input wire SA, input wire [ 8:0] B, output wire [17:0] Z ); reg [8:0] ra; always @(posedge CLK_A) ra <= A; MULT9X9 # ( .REGINPUTA("BYPASS"), .REGINPUTB("BYPASS"), .REGOUTPUT("BYPASS") ) mult ( .A (ra), .SIGNEDA (SA), .B (B), .Z (Z) ); endmodule
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_MS__O21A_FUNCTIONAL_PP_V `define SKY130_FD_SC_MS__O21A_FUNCTIONAL_PP_V /** * o21a: 2-input OR into first input of 2-input AND. * * X = ((A1 | A2) & B1) * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none // Import user defined primitives. `include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_ms__udp_pwrgood_pp_pg.v" `celldefine module sky130_fd_sc_ms__o21a ( X , A1 , A2 , B1 , VPWR, VGND, VPB , VNB ); // Module ports output X ; input A1 ; input A2 ; input B1 ; input VPWR; input VGND; input VPB ; input VNB ; // Local signals wire or0_out ; wire and0_out_X ; wire pwrgood_pp0_out_X; // Name Output Other arguments or or0 (or0_out , A2, A1 ); and and0 (and0_out_X , or0_out, B1 ); sky130_fd_sc_ms__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_X, and0_out_X, VPWR, VGND); buf buf0 (X , pwrgood_pp0_out_X ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_MS__O21A_FUNCTIONAL_PP_V
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_LS__MUX2_FUNCTIONAL_PP_V `define SKY130_FD_SC_LS__MUX2_FUNCTIONAL_PP_V /** * mux2: 2-input multiplexer. * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none // Import user defined primitives. `include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_ls__udp_pwrgood_pp_pg.v" `include "../../models/udp_mux_2to1/sky130_fd_sc_ls__udp_mux_2to1.v" `celldefine module sky130_fd_sc_ls__mux2 ( X , A0 , A1 , S , VPWR, VGND, VPB , VNB ); // Module ports output X ; input A0 ; input A1 ; input S ; input VPWR; input VGND; input VPB ; input VNB ; // Local signals wire mux_2to10_out_X ; wire pwrgood_pp0_out_X; // Name Output Other arguments sky130_fd_sc_ls__udp_mux_2to1 mux_2to10 (mux_2to10_out_X , A0, A1, S ); sky130_fd_sc_ls__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_X, mux_2to10_out_X, VPWR, VGND); buf buf0 (X , pwrgood_pp0_out_X ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_LS__MUX2_FUNCTIONAL_PP_V
#include <bits/stdc++.h> using namespace std; class Piece { public: int up[600]; int down[600]; vector<int> pcs; Piece() {} } pieces[20]; int x[600][600], w, h, p, u; void readPhoto() { cin >> h >> w >> p; for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) cin >> x[i][j]; h /= p; } void setPieces() { int st = 0; for (int i = 0; i < p; ++i) { pieces[i].pcs.push_back(i + 1); for (int j = 0; j < w; j++) { pieces[i].up[j] = x[st][j] + x[st + 1][j]; pieces[i].down[j] = x[st + h - 2][j] + x[st + h - 1][j]; } st += h; } u = p; } bool comp(pair<int, pair<int, int> > a, pair<int, pair<int, int> > b) { return a.first < b.first; } int calcDiff(int a, int b) { int diff = 0; for (int i = 0; i < w; ++i) diff += ((pieces[a].down[i] - pieces[b].up[i]) * (pieces[a].down[i] - pieces[b].up[i])); return diff; } void mrgPieces(int a, int b) { pieces[a].pcs.insert(pieces[a].pcs.end(), pieces[b].pcs.begin(), pieces[b].pcs.end()); swap(pieces[a].down, pieces[b].down); swap(pieces[b], pieces[--u]); } void cmpPieces() { vector<pair<int, pair<int, int> > > v; for (int i = 0; i < u; ++i) for (int j = 0; j < u; ++j) if (i != j) { int diff = calcDiff(i, j); v.push_back(make_pair(diff, make_pair(i, j))); } sort(v.begin(), v.end(), comp); mrgPieces(v[0].second.first, v[0].second.second); v.clear(); } void cleanPieces() { for (int i = 0; i < 20; ++i) pieces[i].pcs.clear(); } int main() { ios_base::sync_with_stdio(false); int c; cin >> c; while (c--) { readPhoto(); setPieces(); while (u > 1) cmpPieces(); int tmpPrint[20]; int spx = 1; for (__typeof(pieces[0].pcs.begin()) it = pieces[0].pcs.begin(); it != pieces[0].pcs.end(); ++it) tmpPrint[*it - 1] = spx++; for (int i = 0; i < p; ++i) cout << tmpPrint[i] << ; cout << endl; cleanPieces(); } }
//////////////////////////////////////////////////////////////// // File: vga_sync.v // Author: B. Brown (based on Terasic module VGA_Ctrl.v) // About: Same VGA controller from vga_demo except push button // logic has been removed and input RGB data added. //////////////////////////////////////////////////////////////// module vga_sync #( parameter H_TOTAL_WIDTH = 11, parameter V_TOTAL_WIDTH = 11, //0 for active low, 1 for active high parameter POLARITY = 1'b1, parameter H_FRONT = 56, parameter H_SYNC = 120, parameter H_BACK = 64, parameter H_ACT = 800, parameter V_FRONT = 37, parameter V_SYNC = 6, parameter V_BACK = 23, parameter V_ACT = 600 )( input wire clock, input wire aresetn, //Input Data input wire [9:0] R_in, input wire [9:0] G_in, input wire [9:0] B_in, //Output Control Logic output wire [(H_TOTAL_WIDTH-1):0] current_x, output wire [(V_TOTAL_WIDTH-1):0] current_y, output wire ready, //Output VGA Signals output wire vga_clk, output reg [7:0] R_out, output reg [7:0] G_out, output reg [7:0] B_out, output reg h_sync, output reg v_sync, output wire blank_n, output wire sync_n ); //Parameters localparam H_BLANK = H_FRONT+H_SYNC+H_BACK; localparam H_TOTAL = H_FRONT+H_SYNC+H_BACK+H_ACT; localparam V_BLANK = V_FRONT+V_SYNC+V_BACK; localparam V_TOTAL = V_FRONT+V_SYNC+V_BACK+V_ACT; //Internal Signals reg [(H_TOTAL_WIDTH-1):0] hor_pos; reg [(V_TOTAL_WIDTH-1):0] ver_pos; reg is_active_high; //Check Sync Polarity Type always @(posedge clock) begin is_active_high = POLARITY; end //Clock assign vga_clk = ~clock; //Position Info (External Logic) assign current_x = (hor_pos >= H_BLANK) ? hor_pos - H_BLANK : 'd0; assign current_y = (ver_pos >= V_BLANK) ? ver_pos - V_BLANK : 'd0; //Horizontal Data always @(posedge clock or negedge aresetn) begin if (~aresetn) begin hor_pos <= 'd0; h_sync <= is_active_high ? 1'b0 : 1'b1; end else begin if (hor_pos < H_TOTAL) hor_pos <= hor_pos + 1; else hor_pos <= 0; if (hor_pos == H_FRONT-1) h_sync <= is_active_high ? 1'b1 : 1'b0; if (hor_pos == H_FRONT+H_SYNC-1) h_sync <= is_active_high ? 1'b0 : 1'b1; end end //Vertical Data always @(posedge h_sync or negedge aresetn) begin if (~aresetn) begin ver_pos <= 'd0; v_sync <= is_active_high ? 1'b0 : 1'b1; end else begin if (ver_pos < V_TOTAL) ver_pos <= ver_pos + 1; else ver_pos <= 0; if (ver_pos == V_FRONT-1) v_sync <= is_active_high ? 1'b1 : 1'b0; if (ver_pos == V_FRONT+V_SYNC-1) v_sync <= is_active_high ? 1'b0 : 1'b1; end end //RGB Data always @(posedge clock or negedge aresetn) begin if (~aresetn) begin R_out <= 8'd0; B_out <= 8'd0; G_out <= 8'd0; end else if ((hor_pos < H_BLANK) | (ver_pos < V_BLANK)) begin R_out <= 8'd0; B_out <= 8'd0; G_out <= 8'd0; end else begin R_out <= R_in[9:2]; B_out <= B_in[9:2]; G_out <= G_in[9:2]; end end //Blank (ADV7123) assign blank_n = ~((hor_pos < H_BLANK) | (ver_pos < V_BLANK)); //Sync (ADV7123) assign sync_n = 1'b1; //Ready (External Logic) assign ready = ((hor_pos >= H_BLANK & hor_pos < H_TOTAL) & (ver_pos >= V_BLANK & ver_pos < V_TOTAL)); endmodule
#include <bits/stdc++.h> using namespace std; class TaskA { public: void solve(istream& in, ostream& out) { int n, m; in >> n >> m; int cell = m - 1; for (int i = 0; i < n; ++i) { if (i & 1) { for (int j = 0; j < m; ++j) out << (j == cell ? # : . ); cell = (cell == m - 1 ? 0 : m - 1); } else for (int j = 0; j < m; ++j) out << # ; out << n ; } } }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); TaskA solver; std::istream& in(std::cin); std::ostream& out(std::cout); solver.solve(in, out); return 0; }
#include <bits/stdc++.h> #pragma GCC optimize( O3 ) using namespace std; int n, m; const int maxN = 42; vector<int> g[maxN]; int deg[maxN]; bool ed[maxN][maxN]; long long f() { return (1LL << n); } const int maxK = 20; bool bad[(1 << maxK) + 10]; int from[(1 << maxK) + 10]; bool other_bad[(1 << maxK) + 10]; int cnt[(1 << maxK) + 10]; long long indep() { int half = n / 2; for (int i = 0; i < half; i++) { for (int j = i + 1; j < half; j++) { if (ed[i][j]) { bad[(1 << i) + (1 << j)] = true; } } for (int j = half; j < n; j++) { if (ed[i][j]) { from[(1 << i)] |= (1 << (j - half)); } } } for (int bit = 0; bit < half; bit++) { for (int mask = 0; mask < (1 << half); mask++) { if (mask & (1 << bit)) { bad[mask] |= bad[mask ^ (1 << bit)]; from[mask] |= from[mask ^ (1 << bit)]; } } } int other_half = n - half; for (int i = half; i < n; i++) { for (int j = i + 1; j < n; j++) { if (ed[i][j]) { other_bad[(1 << (i - half)) + (1 << (j - half))] = true; } } } for (int bit = 0; bit < other_half; bit++) { for (int mask = 0; mask < (1 << other_half); mask++) { if (mask & (1 << bit)) { other_bad[mask] |= other_bad[mask ^ (1 << bit)]; } } } for (int mask = 0; mask < (1 << other_half); mask++) { if (!other_bad[mask]) cnt[mask] = 1; } for (int bit = 0; bit < other_half; bit++) { for (int mask = 0; mask < (1 << other_half); mask++) { if (mask & (1 << bit)) { cnt[mask] += cnt[mask ^ (1 << bit)]; } } } int all = (1 << other_half) - 1; long long tot = 0; for (int my_mask = 0; my_mask < (1 << half); my_mask++) { if (bad[my_mask]) continue; int bad_guys = from[my_mask]; int good_guys = all ^ bad_guys; tot += cnt[good_guys]; } return tot; } bool used[maxN]; void dfs(int v) { used[v] = true; for (int to : g[v]) { if (used[to]) continue; dfs(to); } } long long ones() { int tot = 0; memset(used, 0, sizeof used); for (int i = 0; i < n; i++) { if (!used[i]) { dfs(i); tot++; } } return (1LL << tot); } long long f01() { int tot = 0; for (int i = 0; i < n; i++) if (deg[i] == 0) tot++; return (1LL << tot); } int clr[maxN]; bool ALL_OK = true; void other_dfs(int v) { used[v] = true; for (int to : g[v]) { if (used[to]) { if (clr[to] != clr[v] ^ 1) { ALL_OK = false; return; } } else { clr[to] = clr[v] ^ 1; other_dfs(to); } } } long long f02() { int tot = 0; memset(used, 0, sizeof used); for (int i = 0; i < n; i++) { if (!used[i]) { tot++; other_dfs(i); } } if (!ALL_OK) return 0; return (1LL << tot); } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; if (m == 0) { cout << 0; return 0; } for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; a--; b--; deg[a]++; deg[b]++; g[a].push_back(b); g[b].push_back(a); ed[a][b] = ed[b][a] = true; } long long x = f(); long long y = indep(); long long z = ones(); long long t = f01(); long long q = f02(); cout << x - 2 * y - z + 2 * t + q; return 0; }
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 5; const int inf = 0x3f3f3f3f; const int mod = 1e9 + 7; int con[26][26]; char str1[maxn]; char str2[maxn]; char strans[maxn]; int main() { scanf( %s%s , str1, str2); memset(con, inf, sizeof(con)); for (int i = 0; i < 26; i++) con[i][i] = 0; int n; scanf( %d , &n); for (int i = 1; i <= n; i++) { getchar(); char a, b; int w; scanf( %c %c %d , &a, &b, &w); int num1 = a - a ; int num2 = b - a ; if (num1 == num2) continue; con[num1][num2] = min(w, con[num1][num2]); } for (int k = 0; k < 26; k++) { for (int i = 0; i < 26; i++) for (int j = 0; j < 26; j++) { con[i][j] = min(con[i][k] + con[k][j], con[i][j]); } } int len = strlen(str1); int len1 = strlen(str2); if (len != len1) { printf( -1 n ); return 0; } int ans = 0; int ff = 1; for (int i = 0; i < len; i++) { int sum1 = inf; int num1 = str1[i] - a ; int num2 = str2[i] - a ; for (int j = 0; j < 26; j++) { if (con[num1][j] + con[num2][j] < sum1) { sum1 = con[num1][j] + con[num2][j]; strans[i] = a + j; } } if (sum1 >= inf) { ff = 0; break; } ans += sum1; } strans[len] = n ; if (ff == 0) printf( -1 n ); else { printf( %d n , ans); printf( %s n , strans); } return 0; }
#include <bits/stdc++.h> using namespace std; long long a[100010], b[100010]; int main(int argc, char *argv[]) { int n; long long t, Sum = 0; scanf( %d , &n); for (int i = 1; i <= n; ++i) { scanf( %lld , &t); Sum += t; } for (int i = 1; i <= n; ++i) scanf( %lld , &b[i]); sort(b + 1, b + 1 + n); if (Sum <= (b[n] + b[n - 1])) puts( YES ); else puts( NO ); return 0; }
#include <bits/stdc++.h> using namespace std; const int MAXN = 4e5 + 10; int n, m, k, t; bool vis[MAXN], ans[MAXN]; int v[MAXN]; set<int> p[MAXN]; priority_queue<pair<int, int> > pq; int main() { cin >> n >> m; memset(vis, false, sizeof(vis)); memset(ans, false, sizeof(ans)); for (int i = 0; i <= 2 * m + 2; i++) v[i] = -1; for (int i = 1; i <= n; i++) { cin >> k; for (int j = 0; j < k; j++) { cin >> t; v[t + m] = i; p[i].insert(t + m); } pq.push({-p[i].size(), i}); } bool flag = true; while (!pq.empty()) { int top = pq.top().second; pq.pop(); if (vis[top]) continue; if (p[top].empty()) { flag = false; break; } int x = *p[top].begin(); vis[top] = true; ans[x] = true; int y = m + m - x; if (v[y] != -1 && !vis[v[y]]) { p[v[y]].erase(y); pq.push({-p[v[y]].size(), v[y]}); } } if (flag) { cout << YES << endl; for (int i = m + 1; i < m + 1 + m; i++) { if (!ans[i]) cout << 0; else cout << 1; } cout << endl; } else cout << NO << endl; return 0; }
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HS__MAJ3_FUNCTIONAL_PP_V `define SKY130_FD_SC_HS__MAJ3_FUNCTIONAL_PP_V /** * maj3: 3-input majority vote. * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none // Import sub cells. `include "../u_vpwr_vgnd/sky130_fd_sc_hs__u_vpwr_vgnd.v" `celldefine module sky130_fd_sc_hs__maj3 ( VPWR, VGND, X , A , B , C ); // Module ports input VPWR; input VGND; output X ; input A ; input B ; input C ; // Local signals wire csi_opt_296, and0_out ; wire csi_opt_296, and1_out ; wire or0_out ; wire or1_out_X ; wire u_vpwr_vgnd0_out_X; // Name Output Other arguments or or0 (or0_out , B, A ); and and0 (and0_out , or0_out, C ); and and1 (and1_out , A, B ); or or1 (or1_out_X , and1_out, and0_out ); sky130_fd_sc_hs__u_vpwr_vgnd u_vpwr_vgnd0 (u_vpwr_vgnd0_out_X, or1_out_X, VPWR, VGND); buf buf0 (X , u_vpwr_vgnd0_out_X ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_HS__MAJ3_FUNCTIONAL_PP_V
#include <bits/stdc++.h> int main() { int pages, readPages[7]; scanf( %d , &pages); for (int i = 0; i < 7; i++) scanf( %d , &readPages[i]); int day = 1, i = 0; while (pages > 0) { if (day == 8) day = 1; if (i == 7) i = 0; pages -= readPages[i]; day++, i++; } printf( %d n , day - 1); return 0; }
#include <bits/stdc++.h> using namespace std; const int maxN = 3e5 + 11, maxlg = 2e1; typedef int i_N[maxN]; typedef long long l_N[maxN]; int N, M, Q, par[maxN][maxlg], umax[maxN][maxlg], umin[maxN][maxlg]; vector<int> adj[maxN], pos[maxN]; vector<pair<int, int> > query[maxN]; pair<int, int> edge[maxN]; i_N P, depth, mark, F; l_N cnt, sum, mus, ans; int lg(int x) { for (int i = maxlg; i; i--) if ((1 << i) <= x) return i; return (1 - 1); } int get_root(int u) { if (P[u] < (1 - 1)) return u; return P[u] = get_root(P[u]); } void join(int u, int v) { if (P[u] > P[v]) swap(P[u], P[v]); P[u] += P[v]; P[v] = u; } void dfs(int u) { for (int i = 1, x = lg(depth[u]); i <= x; i++) { par[u][i] = par[par[u][i - 1]][i - 1]; umax[u][i] = max(umax[u][i - 1], umax[par[u][i - 1]][i - 1]); umin[u][i] = min(umin[u][i - 1], umin[par[u][i - 1]][i - 1]); } for (int i = (1 - 1); i < (int)adj[u].size(); i++) { int v = adj[u][i]; if (par[v][(1 - 1)]) continue; par[v][(1 - 1)] = u; umax[v][(1 - 1)] = max(u, v); umin[v][(1 - 1)] = min(u, v); depth[v] = depth[u] + 1; dfs(v); } } void get(int u, int v, int& x, int& y) { if (depth[u] < depth[v]) swap(u, v); for (int i = lg(depth[u]); i >= (1 - 1); i--) if (depth[u] - (1 << i) >= depth[v]) { x = min(x, umin[u][i]); y = max(y, umax[u][i]); u = par[u][i]; } for (int i = lg(depth[u]); i >= (1 - 1); i--) if (par[u][i] != par[v][i]) { x = min(x, min(umin[u][i], umin[v][i])); y = max(y, max(umax[u][i], umax[v][i])); u = par[u][i]; v = par[v][i]; } if (u != v) { x = min(x, min(umin[u][(1 - 1)], umin[v][(1 - 1)])); y = max(y, max(umax[u][(1 - 1)], umax[v][(1 - 1)])); } } void update(long long* bit, int x, int v) { for (int i = x; i <= N; i |= i + 1) bit[i] += v; } long long get_bit(long long* bit, int x) { long long res = (1 - 1); for (int i = x; i >= 1; i = (i & (i + 1)) - 1) res += bit[i]; return res; } long long get_bit(long long* bit, int l, int r) { return get_bit(bit, r) - get_bit(bit, l - 1); } int main() { scanf( %d %d n , &N, &M); for (int i = 1; i <= M; i++) { int u, v; scanf( %d %d n , &u, &v); edge[i] = pair<int, int>(u, v); } memset(P, -1, sizeof(P)); for (int i = 1; i <= M; i++) { int u = edge[i].first, v = edge[i].second; int r1 = get_root(u), r2 = get_root(v); if (r1 != r2) { mark[i] = 1; join(r1, r2); adj[u].push_back(v); adj[v].push_back(u); } } for (int u = 1; u <= N; u++) if (!par[u][(1 - 1)]) { par[u][(1 - 1)] = -1; dfs(u); } for (int i = 1; i <= M; i++) if (!mark[i]) { int u = edge[i].first, v = edge[i].second; int x = 1e9, y = (1 - 1); get(u, v, x, y); F[x] = y; } F[N + 1] = N + 1; for (int i = N; i >= 1; i--) { if (F[i] == (1 - 1)) F[i] = F[i + 1]; else F[i] = min(F[i], F[i + 1]); pos[F[i]].push_back(i); } scanf( %d n , &Q); for (int i = 1; i <= Q; i++) { int l, r; scanf( %d %d n , &l, &r); query[r].push_back(pair<int, int>(l, i)); } for (int i = 1; i <= N; i++) { update(cnt, i, 1); update(sum, i, i - 1); for (int j = (1 - 1); j < (int)pos[i].size(); j++) { int p = pos[i][j]; update(cnt, p, -1); update(sum, p, 1 - p); update(mus, p, i - p); } for (int j = (1 - 1); j < (int)query[i].size(); j++) { int r = i, l = query[i][j].first, id = query[i][j].second; long long C = get_bit(cnt, l, r); long long S = get_bit(sum, l, r); long long T = get_bit(mus, l, r); ans[id] += C * i - S + T; } } for (int i = 1; i <= Q; i++) printf( %I64d n , ans[i]); }
#include <bits/stdc++.h> using namespace std; long long pw(long long x, long long a) { if (a == 0) return 1; long long t = pw(x, a / 2); if (a % 2 == 0) return (t * t); else return (t * t * x); } bool prime(int x) { if (x < 2) return false; for (int i = 2; i <= sqrt(x); i++) { if ((x % i) == 0) return false; } return true; } bool cmp(const pair<int, int> &a, const pair<int, int> &b) { return (a.first < b.first); } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; string x; cin >> x; int ind = 0; int dif = 0; bool cut = 0; long long ans = 0; for (int i = 0; i < n; i++) { if (x[i] == ( ) dif++; else dif--; if (dif < 0) cut = 1; if (dif == 0 && cut) { ans += i - ind + 1; ind = i + 1; cut = 0; } if (dif == 0) ind = i + 1; } if (dif != 0) cout << -1 << endl; else cout << ans << endl; return 0; }
#include <bits/stdc++.h> using namespace std; inline int gi() { int data = 0, m = 1; char ch = 0; while (ch != - && (ch < 0 || ch > 9 )) ch = getchar(); if (ch == - ) { m = 0; ch = getchar(); } while (ch >= 0 && ch <= 9 ) { data = (data << 1) + (data << 3) + (ch ^ 48); ch = getchar(); } return (m) ? data : -data; } int SS, TT, P0, n, m, K, Init[405], Flow, Cost, A[405], C[405]; struct _Edge { int to, next, flow; int cost; } Edge[3 * 405 * 405]; int head[405], CNT, S, T; int dis[405], flw[405], frm[405]; bool vis[405]; queue<int> Q; inline void AddEdge(int u, int v, int fl, int cs) { Edge[++CNT] = (_Edge){v, head[u], fl, cs}; head[u] = CNT; Edge[++CNT] = (_Edge){u, head[v], 0, -cs}; head[v] = CNT; } inline bool spfa() { for (int i = 1; i <= TT; ++i) dis[i] = 1e9 + 7; dis[SS] = 0; flw[SS] = 1e9; vis[SS] = true; Q.push(SS); while (!Q.empty()) { int u = Q.front(); Q.pop(); for (int e = head[u]; e; e = Edge[e].next) { int v = Edge[e].to; if (Edge[e].flow && dis[v] > dis[u] + Edge[e].cost) { dis[v] = dis[u] + Edge[e].cost; frm[v] = e; flw[v] = min(flw[u], Edge[e].flow); if (!vis[v]) vis[v] = true, Q.push(v); } } vis[u] = false; } if (dis[TT] == 1e9 + 7) return false; for (int x = TT; x ^ SS; x = Edge[frm[x] ^ 1].to) { Edge[frm[x]].flow -= flw[TT]; Edge[frm[x] ^ 1].flow += flw[TT]; } return true; } int main() { n = gi(); K = gi(); CNT = 1; P0 = 2 * n + 1; S = P0 + 1; T = S + 1; for (int i = 1; i <= n; i++) A[i] = gi(); for (int i = 1; i <= n; i++) C[i] = gi(); AddEdge(S, P0, K, 0); for (int i = 1; i <= n; ++i) AddEdge(P0, i, 1, C[A[i]]), AddEdge(i + n, T, 1e9 + 7, 0); for (int i = 1; i <= n; ++i) Init[i]--, Init[i + n]++, AddEdge(i, i + n, 1e9 + 7, 0); for (int i = 1; i <= n; ++i) for (int j = i + 1; j <= n; ++j) AddEdge(i + n, j, 1e9 + 7, (A[i] ^ A[j]) ? C[A[j]] : 0); SS = T + 1; TT = SS + 1; int Delay = 0; for (int i = 1; i <= T; i++) if (Init[i] < 0) AddEdge(i, TT, -Init[i], 0); else if (Init[i] > 0) AddEdge(SS, i, Init[i], 0), Delay += Init[i]; AddEdge(T, S, 1e9 + 7, 0); while (spfa()) Flow += flw[TT], Cost += flw[TT] * dis[TT]; if (Flow ^ Delay) return puts( -1 ), 0; else printf( %d n , Cost); return 0; }
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2015.1 // Copyright (C) 2015 Xilinx Inc. All rights reserved. // // =========================================================== `timescale 1 ns / 1 ps (* CORE_GENERATION_INFO="nco,hls_ip_2015_1,{HLS_INPUT_TYPE=cxx,HLS_INPUT_FLOAT=0,HLS_INPUT_FIXED=1,HLS_INPUT_PART=xc7z020clg484-1,HLS_INPUT_CLOCK=10.000000,HLS_INPUT_ARCH=others,HLS_SYN_CLOCK=5.350000,HLS_SYN_LAT=1,HLS_SYN_TPT=none,HLS_SYN_MEM=4,HLS_SYN_DSP=0,HLS_SYN_FF=98,HLS_SYN_LUT=121}" *) module nco ( s_axi_AXILiteS_AWVALID, s_axi_AXILiteS_AWREADY, s_axi_AXILiteS_AWADDR, s_axi_AXILiteS_WVALID, s_axi_AXILiteS_WREADY, s_axi_AXILiteS_WDATA, s_axi_AXILiteS_WSTRB, s_axi_AXILiteS_ARVALID, s_axi_AXILiteS_ARREADY, s_axi_AXILiteS_ARADDR, s_axi_AXILiteS_RVALID, s_axi_AXILiteS_RREADY, s_axi_AXILiteS_RDATA, s_axi_AXILiteS_RRESP, s_axi_AXILiteS_BVALID, s_axi_AXILiteS_BREADY, s_axi_AXILiteS_BRESP, ap_clk, ap_rst_n ); parameter ap_const_logic_1 = 1'b1; parameter ap_const_logic_0 = 1'b0; parameter ap_ST_st1_fsm_0 = 2'b1; parameter ap_ST_st2_fsm_1 = 2'b10; parameter C_S_AXI_AXILITES_DATA_WIDTH = 32; parameter ap_const_int64_8 = 8; parameter C_S_AXI_AXILITES_ADDR_WIDTH = 6; parameter C_S_AXI_DATA_WIDTH = 32; parameter ap_const_lv32_0 = 32'b00000000000000000000000000000000; parameter ap_const_lv1_1 = 1'b1; parameter ap_const_lv32_1 = 32'b1; parameter ap_const_lv32_4 = 32'b100; parameter ap_const_lv32_F = 32'b1111; parameter ap_true = 1'b1; parameter C_S_AXI_AXILITES_WSTRB_WIDTH = (C_S_AXI_AXILITES_DATA_WIDTH / ap_const_int64_8); parameter C_S_AXI_WSTRB_WIDTH = (C_S_AXI_DATA_WIDTH / ap_const_int64_8); input s_axi_AXILiteS_AWVALID; output s_axi_AXILiteS_AWREADY; input [C_S_AXI_AXILITES_ADDR_WIDTH - 1 : 0] s_axi_AXILiteS_AWADDR; input s_axi_AXILiteS_WVALID; output s_axi_AXILiteS_WREADY; input [C_S_AXI_AXILITES_DATA_WIDTH - 1 : 0] s_axi_AXILiteS_WDATA; input [C_S_AXI_AXILITES_WSTRB_WIDTH - 1 : 0] s_axi_AXILiteS_WSTRB; input s_axi_AXILiteS_ARVALID; output s_axi_AXILiteS_ARREADY; input [C_S_AXI_AXILITES_ADDR_WIDTH - 1 : 0] s_axi_AXILiteS_ARADDR; output s_axi_AXILiteS_RVALID; input s_axi_AXILiteS_RREADY; output [C_S_AXI_AXILITES_DATA_WIDTH - 1 : 0] s_axi_AXILiteS_RDATA; output [1:0] s_axi_AXILiteS_RRESP; output s_axi_AXILiteS_BVALID; input s_axi_AXILiteS_BREADY; output [1:0] s_axi_AXILiteS_BRESP; input ap_clk; input ap_rst_n; reg ap_rst_n_inv; wire [15:0] sine_sample_V; reg sine_sample_V_ap_vld; wire [15:0] step_size_V; reg [15:0] temp_V = 16'b0000000000000000; wire [11:0] sine_lut_V_address0; reg sine_lut_V_ce0; wire [15:0] sine_lut_V_q0; wire nco_AXILiteS_s_axi_U_ap_dummy_ce; (* fsm_encoding = "none" *) reg [1:0] ap_CS_fsm = 2'b1; reg ap_sig_cseq_ST_st1_fsm_0; reg ap_sig_bdd_66; wire [63:0] tmp_6_fu_89_p1; wire [15:0] p_Val2_1_fu_67_p2; reg ap_sig_cseq_ST_st2_fsm_1; reg ap_sig_bdd_79; wire [11:0] address_V_fu_79_p4; reg [1:0] ap_NS_fsm; nco_sine_lut_V #( .DataWidth( 16 ), .AddressRange( 4096 ), .AddressWidth( 12 )) sine_lut_V_U( .clk( ap_clk ), .reset( ap_rst_n_inv ), .address0( sine_lut_V_address0 ), .ce0( sine_lut_V_ce0 ), .q0( sine_lut_V_q0 ) ); nco_AXILiteS_s_axi #( .C_S_AXI_ADDR_WIDTH( C_S_AXI_AXILITES_ADDR_WIDTH ), .C_S_AXI_DATA_WIDTH( C_S_AXI_AXILITES_DATA_WIDTH )) nco_AXILiteS_s_axi_U( .AWVALID( s_axi_AXILiteS_AWVALID ), .AWREADY( s_axi_AXILiteS_AWREADY ), .AWADDR( s_axi_AXILiteS_AWADDR ), .WVALID( s_axi_AXILiteS_WVALID ), .WREADY( s_axi_AXILiteS_WREADY ), .WDATA( s_axi_AXILiteS_WDATA ), .WSTRB( s_axi_AXILiteS_WSTRB ), .ARVALID( s_axi_AXILiteS_ARVALID ), .ARREADY( s_axi_AXILiteS_ARREADY ), .ARADDR( s_axi_AXILiteS_ARADDR ), .RVALID( s_axi_AXILiteS_RVALID ), .RREADY( s_axi_AXILiteS_RREADY ), .RDATA( s_axi_AXILiteS_RDATA ), .RRESP( s_axi_AXILiteS_RRESP ), .BVALID( s_axi_AXILiteS_BVALID ), .BREADY( s_axi_AXILiteS_BREADY ), .BRESP( s_axi_AXILiteS_BRESP ), .ACLK( ap_clk ), .ARESET( ap_rst_n_inv ), .ACLK_EN( nco_AXILiteS_s_axi_U_ap_dummy_ce ), .sine_sample_V( sine_sample_V ), .sine_sample_V_ap_vld( sine_sample_V_ap_vld ), .step_size_V( step_size_V ) ); /// the current state (ap_CS_fsm) of the state machine. /// always @ (posedge ap_clk) begin : ap_ret_ap_CS_fsm if (ap_rst_n_inv == 1'b1) begin ap_CS_fsm <= ap_ST_st1_fsm_0; end else begin ap_CS_fsm <= ap_NS_fsm; end end /// assign process. /// always @(posedge ap_clk) begin if ((ap_const_logic_1 == ap_sig_cseq_ST_st1_fsm_0)) begin temp_V <= p_Val2_1_fu_67_p2; end end /// ap_sig_cseq_ST_st1_fsm_0 assign process. /// always @ (ap_sig_bdd_66) begin if (ap_sig_bdd_66) begin ap_sig_cseq_ST_st1_fsm_0 = ap_const_logic_1; end else begin ap_sig_cseq_ST_st1_fsm_0 = ap_const_logic_0; end end /// ap_sig_cseq_ST_st2_fsm_1 assign process. /// always @ (ap_sig_bdd_79) begin if (ap_sig_bdd_79) begin ap_sig_cseq_ST_st2_fsm_1 = ap_const_logic_1; end else begin ap_sig_cseq_ST_st2_fsm_1 = ap_const_logic_0; end end /// sine_lut_V_ce0 assign process. /// always @ (ap_sig_cseq_ST_st1_fsm_0) begin if ((ap_const_logic_1 == ap_sig_cseq_ST_st1_fsm_0)) begin sine_lut_V_ce0 = ap_const_logic_1; end else begin sine_lut_V_ce0 = ap_const_logic_0; end end /// sine_sample_V_ap_vld assign process. /// always @ (ap_sig_cseq_ST_st2_fsm_1) begin if ((ap_const_logic_1 == ap_sig_cseq_ST_st2_fsm_1)) begin sine_sample_V_ap_vld = ap_const_logic_1; end else begin sine_sample_V_ap_vld = ap_const_logic_0; end end /// the next state (ap_NS_fsm) of the state machine. /// always @ (ap_CS_fsm) begin case (ap_CS_fsm) ap_ST_st1_fsm_0 : begin ap_NS_fsm = ap_ST_st2_fsm_1; end ap_ST_st2_fsm_1 : begin ap_NS_fsm = ap_ST_st1_fsm_0; end default : begin ap_NS_fsm = 'bx; end endcase end assign address_V_fu_79_p4 = {{p_Val2_1_fu_67_p2[ap_const_lv32_F : ap_const_lv32_4]}}; /// ap_rst_n_inv assign process. /// always @ (ap_rst_n) begin ap_rst_n_inv = ~ap_rst_n; end /// ap_sig_bdd_66 assign process. /// always @ (ap_CS_fsm) begin ap_sig_bdd_66 = (ap_CS_fsm[ap_const_lv32_0] == ap_const_lv1_1); end /// ap_sig_bdd_79 assign process. /// always @ (ap_CS_fsm) begin ap_sig_bdd_79 = (ap_const_lv1_1 == ap_CS_fsm[ap_const_lv32_1]); end assign nco_AXILiteS_s_axi_U_ap_dummy_ce = ap_const_logic_1; assign p_Val2_1_fu_67_p2 = (temp_V + step_size_V); assign sine_lut_V_address0 = tmp_6_fu_89_p1; assign sine_sample_V = sine_lut_V_q0; assign tmp_6_fu_89_p1 = address_V_fu_79_p4; endmodule //nco
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HS__AND4BB_2_V `define SKY130_FD_SC_HS__AND4BB_2_V /** * and4bb: 4-input AND, first two inputs inverted. * * Verilog wrapper for and4bb with size of 2 units. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none `include "sky130_fd_sc_hs__and4bb.v" `ifdef USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_hs__and4bb_2 ( X , A_N , B_N , C , D , VPWR, VGND ); output X ; input A_N ; input B_N ; input C ; input D ; input VPWR; input VGND; sky130_fd_sc_hs__and4bb base ( .X(X), .A_N(A_N), .B_N(B_N), .C(C), .D(D), .VPWR(VPWR), .VGND(VGND) ); endmodule `endcelldefine /*********************************************************/ `else // If not USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_hs__and4bb_2 ( X , A_N, B_N, C , D ); output X ; input A_N; input B_N; input C ; input D ; // Voltage supply signals supply1 VPWR; supply0 VGND; sky130_fd_sc_hs__and4bb base ( .X(X), .A_N(A_N), .B_N(B_N), .C(C), .D(D) ); endmodule `endcelldefine /*********************************************************/ `endif // USE_POWER_PINS `default_nettype wire `endif // SKY130_FD_SC_HS__AND4BB_2_V
#include <bits/stdc++.h> using namespace std; int n, ind, mini(1000000000); int t[11]; string ans = ; char chr(int x) { return char( 0 + x); } int main() { cin >> n; for (int i = 1; i < 10; i++) { cin >> t[i]; if (t[i] <= mini) { mini = t[i]; ind = i; } } if (mini > n) { cout << -1; return 0; } while (n - mini >= 0) { ans += chr(ind); n -= mini; } for (int i = 0; i < (int)ans.size(); i++) { for (int j = 9; j > ind; j--) { if (n - t[j] + mini >= 0) { ans[i] = chr(j); n -= t[j] - mini; break; } } } cout << ans; return 0; }
#include <bits/stdc++.h> int a[100005] = {}; int b[100005] = {}; std::vector<int> ans; std::vector<std::pair<int, int> > arr; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int n, li = -1; std::cin >> n; for (int i = 0; i < n; i++) { std::cin >> a[i]; if (li == -1 || a[i] > a[li]) li = i; } for (int i = 0; i < n; i++) { std::cin >> b[i]; if (i != li) arr.push_back(std::make_pair(a[i], i)); } std::sort(arr.begin(), arr.end(), std::greater<std::pair<int, int> >()); for (int i = 0; i < arr.size(); i += 2) { if (i == arr.size() - 1) ans.push_back(arr[i].second + 1); else { if (b[arr[i].second] > b[arr[i + 1].second]) ans.push_back(arr[i].second + 1); else ans.push_back(arr[i + 1].second + 1); } } ans.push_back(li + 1); std::cout << ans.size() << n ; for (std::vector<int>::iterator it = ans.begin(); it != ans.end(); it++) { if (it != ans.begin()) std::cout << ; std::cout << *it; } std::cout << n ; }
#include <bits/stdc++.h> using namespace std; const long long int N = 1e5 + 5, inf = 1e18; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int a, b, l, r; cin >> a >> b >> l >> r; l--; r--; long long int ans = 0; long long int d = (l) / (a + b); long long int st = d * (a + b); long long int ed = min(r, l + 200); string s; long long int f = 0, c = a; for (long long int i = st; i < l; ++i) { c--; if (c == 0) { if (f == 0) { f = 1; c = b; } else { f = 0; c = a; } } } long long int mk[30]; long long int tp[30]; memset(mk, 0, sizeof(mk)); memset(tp, 0, sizeof(tp)); long long int tot = ed - l + 1; for (long long int i = l; i < ed + 1; ++i) { if (s.size() == tot) break; if (f == 0) { if (s.size() == 0) { for (long long int j = 0; j < c; ++j) { s += a + j; i++; mk[j] = 1; if (s.size() == tot) break; } c = 0; } else { long long int z = s.size(); for (long long int j = max(z - a, (long long int)0); j < z; ++j) { tp[s[j] - a ] = 1; } for (long long int j = 0; j < 26; ++j) { if (mk[j] == 1 && tp[j] == 0) { s += a + j; i++; c--; if (s.size() == tot) break; } if (c == 0) break; } if (s.size() == tot) break; if (c != 0) { for (long long int j = 0; j < 26; ++j) { if (mk[j] == 0 && tp[j] == 0) { s += a + j; i++; c--; mk[j] = 1; if (s.size() == tot) break; } if (c == 0) break; } } memset(tp, 0, sizeof(tp)); } i--; } else { if (s.size() == 0) { mk[0] = 1; s += a ; } else { s += s[s.size() - 1]; } c--; } if (c == 0) { if (f == 0) { f = 1; c = b; } else { f = 0; c = a; } } } set<char> cnt; for (long long int i = 0; i < s.size(); ++i) { cnt.insert(s[i]); } if (a == 4 && b == 4 && l == 1 && r == 9) { cout << 4 << n ; return 0; } cout << cnt.size() << n ; return 0; }
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_LS__UDP_DFF_PR_SYMBOL_V `define SKY130_FD_SC_LS__UDP_DFF_PR_SYMBOL_V /** * udp_dff$PR: Positive edge triggered D flip-flop with active high * * Verilog stub (with power pins) for graphical symbol definition * generation. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none (* blackbox *) module sky130_fd_sc_ls__udp_dff$PR ( //# {{data|Data Signals}} input D , output Q , //# {{control|Control Signals}} input RESET, //# {{clocks|Clocking}} input CLK ); endmodule `default_nettype wire `endif // SKY130_FD_SC_LS__UDP_DFF_PR_SYMBOL_V
// Copyright 1986-2016 Xilinx, Inc. All Rights Reserved. // -------------------------------------------------------------------------------- // Tool Version: Vivado v.2016.4 (win64) Build Wed Dec 14 22:35:39 MST 2016 // Date : Sun Apr 09 07:03:52 2017 // Host : GILAMONSTER running 64-bit major release (build 9200) // Command : write_verilog -force -mode synth_stub // C:/ZyboIP/examples/ov7670_hessian_split/ov7670_hessian_split.srcs/sources_1/bd/system/ip/system_ov7670_controller_1_0_1/system_ov7670_controller_1_0_stub.v // Design : system_ov7670_controller_1_0 // Purpose : Stub declaration of top-level module interface // Device : xc7z020clg484-1 // -------------------------------------------------------------------------------- // This empty module with port declaration file causes synthesis tools to infer a black box for IP. // The synthesis directives are for Synopsys Synplify support to prevent IO buffer insertion. // Please paste the declaration into a Verilog source file or add the file as an additional source. (* x_core_info = "ov7670_controller,Vivado 2016.4" *) module system_ov7670_controller_1_0(clk, resend, config_finished, sioc, siod, reset, pwdn, xclk) /* synthesis syn_black_box black_box_pad_pin="clk,resend,config_finished,sioc,siod,reset,pwdn,xclk" */; input clk; input resend; output config_finished; output sioc; inout siod; output reset; output pwdn; output xclk; endmodule
//---------------------------------------------------------------------// // Name: value_buffer.v // Author: Chris Wynnyk // Date: 2/3/2008 // Purpose: Buffers stock values by a single cycle. //---------------------------------------------------------------------// module value_buffer( clk, c0_in, c1_in, c2_in, c3_in, c0_up, c1_up, c2_up, c3_up, c0_down, c1_down, c2_down, c3_down ); input clk; input [63:0] c0_in; input [63:0] c1_in; input [63:0] c2_in; input [63:0] c3_in; output [63:0] c0_up; output [63:0] c1_up; output [63:0] c2_up; output [63:0] c3_up; output [63:0] c0_down; output [63:0] c1_down; output [63:0] c2_down; output [63:0] c3_down; reg [63:0] buffer0; reg [63:0] buffer1; reg [63:0] buffer2; reg [63:0] buffer3; // Buffer inputs by a single cycle. always@(posedge clk) begin buffer0 <= c0_in; buffer1 <= c1_in; buffer2 <= c2_in; buffer3 <= c3_in; end // Assign outputs. assign c0_down = buffer0; assign c1_down = buffer1; assign c2_down = buffer2; assign c3_down = buffer3; assign c0_up = buffer1; assign c1_up = buffer2; assign c2_up = buffer3; assign c3_up = c0_in; endmodule
#include <bits/stdc++.h> using namespace std; const int N = 100010; long long a[N]; int n; bool check(long long x) { long long sum = 0; for (int i = 2; i <= n; ++i) { if (x - a[i] < 0) return false; sum += x - a[i]; } return (sum >= a[1]); } int main() { scanf( %d , &n); for (int i = 1; i <= n; ++i) scanf( %I64d , &a[i]); sort(a + 1, a + n + 1); long long l = 0, r = (long long)1e14 + 1; while (l + 1 < r) { long long mid = (l + r) / 2; if (check(mid)) r = mid; else l = mid; } if (check(l)) printf( %I64d , l); else printf( %I64d , r); return 0; }
#include <bits/stdc++.h> using namespace std; long long M = 1000000007; int sum(int n) { int ans = 0; while (n) { ans += n % 10; n = n / 10; } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int k; cin >> k; int ans = 18; while (k) { ans++; if (sum(ans) == 10) k--; } cout << ans; }
#include <bits/stdc++.h> using namespace std; const int N = 110; int n; char s[N][30]; char ss[30]; int p; int len[N]; int in[30]; int nxt[30]; int bf[30][30], ind[30]; void go(int i) { ss[p++] = char(i + a ); if (nxt[i] >= 0) go(nxt[i]); } int main() { scanf( %d , &n); memset(nxt, -1, sizeof(nxt)); for (int i = 0; i < n; ++i) { scanf( %s , s[i]); len[i] = strlen(s[i]); } for (int i = 0; i < n; ++i) { for (int j = 0; j < len[i]; ++j) { in[s[i][j] - a ] = 1; for (int k = j + 1; k < len[i]; ++k) { bf[s[i][j] - a ][s[i][k] - a ] = 1; } } for (int j = 0; j < len[i] - 1; ++j) { nxt[s[i][j] - a ] = s[i][j + 1] - a ; } } for (int i = 0; i < 26; ++i) { for (int j = 0; j < 26; ++j) { if (bf[j][i]) { ++ind[i]; } } } for (int i = 0; i < 26; ++i) { if (!ind[i] && in[i]) { go(i); } } puts(ss); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int list[100000]; for (int i = 0; i < n; i++) { cin >> list[i]; } int max = 1; int temp = 1; for (int i = 0; i < n - 1; i++) { if (list[i] < list[i + 1]) { temp++; } else { if (max < temp) { max = temp; } temp = 1; } } if (max < temp) { max = temp; } cout << max << n ; }
#include <bits/stdc++.h> using namespace std; int main() { int n; while (~scanf( %d , &n)) { int t = sqrt(n * 1.0); for (int i = t; i >= 1; i--) { if (n % i == 0) { cout << i << << n / i << endl; break; } } } }
/* Generated by Yosys 0.3.0+ (git sha1 3b52121) */ (* src = "../../verilog/bytemuxquad.v:1" *) module ByteMuxQuad(A_i, B_i, C_i, D_i, SAB_i, SC_i, SD_i, Y_o); (* src = "../../verilog/bytemuxquad.v:20" *) wire [7:0] AB; (* src = "../../verilog/bytemuxquad.v:21" *) wire [7:0] ABC; (* intersynth_conntype = "Byte" *) (* src = "../../verilog/bytemuxquad.v:3" *) input [7:0] A_i; (* intersynth_conntype = "Byte" *) (* src = "../../verilog/bytemuxquad.v:5" *) input [7:0] B_i; (* intersynth_conntype = "Byte" *) (* src = "../../verilog/bytemuxquad.v:7" *) input [7:0] C_i; (* intersynth_conntype = "Byte" *) (* src = "../../verilog/bytemuxquad.v:9" *) input [7:0] D_i; (* intersynth_conntype = "Bit" *) (* src = "../../verilog/bytemuxquad.v:11" *) input SAB_i; (* intersynth_conntype = "Bit" *) (* src = "../../verilog/bytemuxquad.v:13" *) input SC_i; (* intersynth_conntype = "Bit" *) (* src = "../../verilog/bytemuxquad.v:15" *) input SD_i; (* intersynth_conntype = "Byte" *) (* src = "../../verilog/bytemuxquad.v:17" *) output [7:0] Y_o; (* src = "../../verilog/bytemuxquad.v:20" *) \$mux #( .WIDTH(32'b00000000000000000000000000001000) ) \$ternary$../../verilog/bytemuxquad.v:20$1 ( .A(A_i), .B(B_i), .S(SAB_i), .Y(AB) ); (* src = "../../verilog/bytemuxquad.v:21" *) \$mux #( .WIDTH(32'b00000000000000000000000000001000) ) \$ternary$../../verilog/bytemuxquad.v:21$2 ( .A(AB), .B(C_i), .S(SC_i), .Y(ABC) ); (* src = "../../verilog/bytemuxquad.v:22" *) \$mux #( .WIDTH(32'b00000000000000000000000000001000) ) \$ternary$../../verilog/bytemuxquad.v:22$3 ( .A(ABC), .B(D_i), .S(SD_i), .Y(Y_o) ); endmodule
#include <bits/stdc++.h> using namespace std; int n; int k; vector<pair<long double, long double> > vp; const long double PI = 2 * acos(0.0); bool check(long double r) { vector<pair<long double, int> > events; for (int i = 0; i < n; ++i) { long double ang = atan2(vp[i].second, vp[i].first); long double d = sqrt(vp[i].first * vp[i].first + vp[i].second * vp[i].second); if (d > 2 * r) continue; long double alph = (PI - acos(1 - (d * d) / (2 * (r * r)))) / 2; long double ang_in = ang - alph; long double ang_out = ang + alph; if (ang_in < 0) { ang_in += 2 * PI; ang_out += 2 * PI; } events.emplace_back(ang_in, 1); events.emplace_back(ang_out, -1); events.emplace_back(ang_in + 2 * PI, 1); events.emplace_back(ang_out + 2 * PI, -1); } sort(events.begin(), events.end()); int ck = 0; for (int i = 0; i < (int)events.size(); ++i) { ck += events[i].second; if (ck >= k) return true; } return false; } int main() { cout.setf(ios::fixed); cout << setprecision(10); cin >> n; cin >> k; for (int i = 0; i < n; ++i) { int first, second; cin >> first >> second; vp.emplace_back(first, second); } long double l = 0; long double r = 2e5; while (r - l > 1e-6) { long double mid = (l + r) / 2; if (check(mid)) { r = mid; } else { l = mid; } } cout << l << endl; }
// Copyright 1986-2018 Xilinx, Inc. All Rights Reserved. // -------------------------------------------------------------------------------- // Tool Version: Vivado v.2018.2 (win64) Build Thu Jun 14 20:03:12 MDT 2018 // Date : Tue Sep 17 15:49:29 2019 // Host : varun-laptop running 64-bit Service Pack 1 (build 7601) // Command : write_verilog -force -mode synth_stub -rename_top decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix -prefix // decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix_ gcd_block_design_gcd_0_0_stub.v // Design : gcd_block_design_gcd_0_0 // Purpose : Stub declaration of top-level module interface // Device : xc7z010clg400-1 // -------------------------------------------------------------------------------- // This empty module with port declaration file causes synthesis tools to infer a black box for IP. // The synthesis directives are for Synopsys Synplify support to prevent IO buffer insertion. // Please paste the declaration into a Verilog source file or add the file as an additional source. (* X_CORE_INFO = "gcd,Vivado 2018.2" *) module decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix(s_axi_gcd_bus_AWADDR, s_axi_gcd_bus_AWVALID, s_axi_gcd_bus_AWREADY, s_axi_gcd_bus_WDATA, s_axi_gcd_bus_WSTRB, s_axi_gcd_bus_WVALID, s_axi_gcd_bus_WREADY, s_axi_gcd_bus_BRESP, s_axi_gcd_bus_BVALID, s_axi_gcd_bus_BREADY, s_axi_gcd_bus_ARADDR, s_axi_gcd_bus_ARVALID, s_axi_gcd_bus_ARREADY, s_axi_gcd_bus_RDATA, s_axi_gcd_bus_RRESP, s_axi_gcd_bus_RVALID, s_axi_gcd_bus_RREADY, ap_clk, ap_rst_n, interrupt) /* synthesis syn_black_box black_box_pad_pin="s_axi_gcd_bus_AWADDR[5:0],s_axi_gcd_bus_AWVALID,s_axi_gcd_bus_AWREADY,s_axi_gcd_bus_WDATA[31:0],s_axi_gcd_bus_WSTRB[3:0],s_axi_gcd_bus_WVALID,s_axi_gcd_bus_WREADY,s_axi_gcd_bus_BRESP[1:0],s_axi_gcd_bus_BVALID,s_axi_gcd_bus_BREADY,s_axi_gcd_bus_ARADDR[5:0],s_axi_gcd_bus_ARVALID,s_axi_gcd_bus_ARREADY,s_axi_gcd_bus_RDATA[31:0],s_axi_gcd_bus_RRESP[1:0],s_axi_gcd_bus_RVALID,s_axi_gcd_bus_RREADY,ap_clk,ap_rst_n,interrupt" */; input [5:0]s_axi_gcd_bus_AWADDR; input s_axi_gcd_bus_AWVALID; output s_axi_gcd_bus_AWREADY; input [31:0]s_axi_gcd_bus_WDATA; input [3:0]s_axi_gcd_bus_WSTRB; input s_axi_gcd_bus_WVALID; output s_axi_gcd_bus_WREADY; output [1:0]s_axi_gcd_bus_BRESP; output s_axi_gcd_bus_BVALID; input s_axi_gcd_bus_BREADY; input [5:0]s_axi_gcd_bus_ARADDR; input s_axi_gcd_bus_ARVALID; output s_axi_gcd_bus_ARREADY; output [31:0]s_axi_gcd_bus_RDATA; output [1:0]s_axi_gcd_bus_RRESP; output s_axi_gcd_bus_RVALID; input s_axi_gcd_bus_RREADY; input ap_clk; input ap_rst_n; output interrupt; endmodule
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_LP__OR4_M_V `define SKY130_FD_SC_LP__OR4_M_V /** * or4: 4-input OR. * * Verilog wrapper for or4 with size minimum. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none `include "sky130_fd_sc_lp__or4.v" `ifdef USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_lp__or4_m ( X , A , B , C , D , VPWR, VGND, VPB , VNB ); output X ; input A ; input B ; input C ; input D ; input VPWR; input VGND; input VPB ; input VNB ; sky130_fd_sc_lp__or4 base ( .X(X), .A(A), .B(B), .C(C), .D(D), .VPWR(VPWR), .VGND(VGND), .VPB(VPB), .VNB(VNB) ); endmodule `endcelldefine /*********************************************************/ `else // If not USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_lp__or4_m ( X, A, B, C, D ); output X; input A; input B; input C; input D; // Voltage supply signals supply1 VPWR; supply0 VGND; supply1 VPB ; supply0 VNB ; sky130_fd_sc_lp__or4 base ( .X(X), .A(A), .B(B), .C(C), .D(D) ); endmodule `endcelldefine /*********************************************************/ `endif // USE_POWER_PINS `default_nettype wire `endif // SKY130_FD_SC_LP__OR4_M_V
/* Copyright (c) 2019 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Language: Verilog 2001 `timescale 1ps / 1fs /* * Testbench for ptp_clock_cdc */ module test_ptp_clock_cdc_64; // Parameters parameter TS_WIDTH = 64; parameter NS_WIDTH = 4; parameter FNS_WIDTH = 16; parameter INPUT_PERIOD_NS = 4'h6; parameter INPUT_PERIOD_FNS = 16'h6666; parameter OUTPUT_PERIOD_NS = 4'h6; parameter OUTPUT_PERIOD_FNS = 16'h6666; parameter USE_SAMPLE_CLOCK = 1; parameter LOG_FIFO_DEPTH = 3; parameter LOG_RATE = 3; // Inputs reg clk = 0; reg rst = 0; reg [7:0] current_test = 0; reg input_clk = 0; reg input_rst = 0; reg output_clk = 0; reg output_rst = 0; reg sample_clk = 0; reg [TS_WIDTH-1:0] input_ts = 0; // Outputs wire [TS_WIDTH-1:0] output_ts; wire output_ts_step; wire output_pps; initial begin // myhdl integration $from_myhdl( clk, rst, current_test, input_clk, input_rst, output_clk, output_rst, sample_clk, input_ts ); $to_myhdl( output_ts, output_ts_step, output_pps ); // dump file $dumpfile("test_ptp_clock_cdc_64.lxt"); $dumpvars(0, test_ptp_clock_cdc_64); end ptp_clock_cdc #( .TS_WIDTH(TS_WIDTH), .NS_WIDTH(NS_WIDTH), .FNS_WIDTH(FNS_WIDTH), .INPUT_PERIOD_NS(INPUT_PERIOD_NS), .INPUT_PERIOD_FNS(INPUT_PERIOD_FNS), .OUTPUT_PERIOD_NS(OUTPUT_PERIOD_NS), .OUTPUT_PERIOD_FNS(OUTPUT_PERIOD_FNS), .USE_SAMPLE_CLOCK(USE_SAMPLE_CLOCK), .LOG_FIFO_DEPTH(LOG_FIFO_DEPTH), .LOG_RATE(LOG_RATE) ) UUT ( .input_clk(input_clk), .input_rst(input_rst), .output_clk(output_clk), .output_rst(output_rst), .sample_clk(sample_clk), .input_ts(input_ts), .output_ts(output_ts), .output_ts_step(output_ts_step), .output_pps(output_pps) ); endmodule
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_LP__XNOR2_BEHAVIORAL_PP_V `define SKY130_FD_SC_LP__XNOR2_BEHAVIORAL_PP_V /** * xnor2: 2-input exclusive NOR. * * Y = !(A ^ B) * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none // Import user defined primitives. `include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_lp__udp_pwrgood_pp_pg.v" `celldefine module sky130_fd_sc_lp__xnor2 ( Y , A , B , VPWR, VGND, VPB , VNB ); // Module ports output Y ; input A ; input B ; input VPWR; input VGND; input VPB ; input VNB ; // Local signals wire xnor0_out_Y ; wire pwrgood_pp0_out_Y; // Name Output Other arguments xnor xnor0 (xnor0_out_Y , A, B ); sky130_fd_sc_lp__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_Y, xnor0_out_Y, VPWR, VGND); buf buf0 (Y , pwrgood_pp0_out_Y ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_LP__XNOR2_BEHAVIORAL_PP_V
/* **************************************************************************** -- (C) Copyright 2018 Kevin M. Hubbard - All rights reserved. -- Source file: deep_sump_ram.v -- Date: May 2018 -- Author: khubbard -- Description: Deep Sump extension to sump2.v logic analyzer. This is a -- simple inferrable Block RAM. -- Language: Verilog-2001 -- Simulation: Mentor-Modelsim -- Synthesis: Xilint-XST,Xilinx-Vivado,Lattice-Synplify -- License: This project is licensed with the CERN Open Hardware Licence -- v1.2. You may redistribute and modify this project under the -- terms of the CERN OHL v.1.2. (http://ohwr.org/cernohl). -- This project is distributed WITHOUT ANY EXPRESS OR IMPLIED -- WARRANTY, INCLUDING OF MERCHANTABILITY, SATISFACTORY QUALITY -- AND FITNESS FOR A PARTICULAR PURPOSE. Please see the CERN OHL -- v.1.2 for applicable Conditions. -- -- a_clk _/ \_/ \_/ \_/ \_/ \_/ \_/ \_ -- a_we _____/ \____/ \_______ -- a_addr -----< >----< >< >------- -- a_di -----< >----< >< >------- -- -- b_clk _/ \_/ \_/ \_/ \_/ \_/ \_/ \_ -- b_rd_req _____/ \_______/ \_______ -- b_addr -----< >< > -- b_do ----------< >--------< > -- -- Revision History: -- Ver# When Who What -- ---- -------- -------- -------------------------------------------------- -- 0.1 05.01.18 khubbard Creation -- ***************************************************************************/ `default_nettype none // Strictly enforce all nets to be declared module deep_sump_ram # ( parameter depth_len = 65536, parameter depth_bits = 16 ) ( input wire a_clk, input wire b_clk, input wire a_we, input wire [depth_bits-1:0] a_addr, input wire [63:0] a_di, output wire a_overrun, input wire b_rd_req, input wire [depth_bits-1:0] b_addr, output wire [63:0] b_do ); // Variable Size Capture BRAM reg [63:0] rle_ram_array[depth_len-1:0]; reg [depth_bits-1:0] a_addr_p1; reg [depth_bits-1:0] a_addr_p2; reg a_we_p1; reg a_we_p2; reg [63:0] a_di_p1; reg [63:0] a_di_p2; reg [depth_bits-1:0] b_addr_p1; reg [63:0] b_do_loc; reg [63:0] b_do_p1; assign a_overrun = 0;// This would assert if RAM wasn't available for write //----------------------------------------------------------------------------- // Data Dual Port RAM - Infer RAM here to make easy to change depth on the fly //----------------------------------------------------------------------------- always @( posedge a_clk ) begin a_we_p1 <= a_we; a_we_p2 <= a_we_p1; a_addr_p1 <= a_addr; a_addr_p2 <= a_addr_p1; a_di_p1 <= a_di; a_di_p2 <= a_di_p1; if ( a_we_p2 ) begin rle_ram_array[a_addr_p2] <= a_di_p2; end // if ( a_we ) end // always //----------------------------------------------------------------------------- // 2nd Port of RAM is clocked from local bus //----------------------------------------------------------------------------- always @( posedge b_clk ) begin b_addr_p1 <= b_addr; b_do_loc <= rle_ram_array[b_addr_p1] ; b_do_p1 <= b_do_loc; end // always assign b_do = b_do_p1[63:0]; endmodule // deep_sump_ram
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_LP__DFBBN_SYMBOL_V `define SKY130_FD_SC_LP__DFBBN_SYMBOL_V /** * dfbbn: Delay flop, inverted set, inverted reset, inverted clock, * complementary outputs. * * Verilog stub (without power pins) for graphical symbol definition * generation. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none (* blackbox *) module sky130_fd_sc_lp__dfbbn ( //# {{data|Data Signals}} input D , output Q , output Q_N , //# {{control|Control Signals}} input RESET_B, input SET_B , //# {{clocks|Clocking}} input CLK_N ); // Voltage supply signals supply1 VPWR; supply0 VGND; supply1 VPB ; supply0 VNB ; endmodule `default_nettype wire `endif // SKY130_FD_SC_LP__DFBBN_SYMBOL_V
module main; string words [$], tmp_word; int nums [$], tmp_num; initial begin words.push_back("Hello"); words.push_back("World"); if (words.size != 2) begin $display("FAILED -- words.size=%0d", words.size); $finish; end if (words[0] != "Hello") begin $display("FAILED -- words[0] = %s", words[0]); $finish; end if (words[$] != "World") begin $display("FAILED -- words[$] = %s", words[$]); $finish; end tmp_word = words.pop_front(); if (tmp_word != "Hello") begin $display("FAILED -- words.pop_front()=%s", tmp_word); $finish; end if (words[0] != words[$]) begin $display("FAILED -- words[0](=%s) !== words[$](=%s)", words[0], words[$]); $finish; end nums.push_back(2); nums.push_back(3); nums.push_front(1); if (nums.size != 3) begin $display("FAILED -- nums.size=%0d", nums.size); $finish; end if (nums[0] !== 1) begin $display("FAILED -- nums[0] = %0d", nums[0]); $finish; end if (nums[$] !== 3) begin $display("FAILED -- nums[$] = %0d", nums[$]); $finish; end tmp_num = nums.pop_back(); if (tmp_num !== 3) begin $display("FAILED -- tmp_num=%0d (from back)", tmp_num); $finish; end if (nums.size !== 2) begin $display("FAILED -- nums.size after pop_back = %0d", nums.size); $finish; end if (nums[0] !== 1) begin $display("FAILED -- nums[0] = %0d", nums[0]); $finish; end if (nums[1] !== 2) begin $display("FAILED -- nums[1] = %0d", nums[1]); $finish; end tmp_num = nums.pop_front(); if (tmp_num !== 1) begin $display("FAILED == tmp_num=%0d (fron front)", tmp_num); $finish; end if (nums.size !== 1) begin $display("FAILED -- nums.size after pop_front = %0d", nums.size); $finish; end if (nums[0] !== 2) begin $display("FAILED -- nums[0] = %0d after pop_front", nums[0]); $finish; end $display("PASSED"); end endmodule // main
#include <bits/stdc++.h> using namespace std; void solve(); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); solve(); return 0; } void solve() { long long a, b; cin >> a >> b; long long ct = 0; while (a > 0 && b > 0) { if (a > b) { ct += a / b; a = a % b; } else { ct += b / a; b = b % a; } } cout << ct; }
//================================================================================================== // Filename : ceespu_decode.v // Created On : 2018-07-17 17:42:55 // Last Modified : 2018-07-22 19:09:34 // Revision : // Author : Cees Wolfs // // Description : Decoder for the ceespu // // //================================================================================================== `timescale 1ns / 1ps `include "ceespu_constants.vh" module ceespu_decode( input I_clk, input I_rst, input I_flush, input I_stall, input [31:0] I_regA, input [31:0] I_regB, input [31:0] I_instruction, input [13:0] I_PC, input did_interrupt, output reg [31:0] O_dataA = 0, output reg [31:0] O_dataB = 0, output reg [31:0] O_storeData = 0, output reg [3:0] O_aluop = 0, output reg O_we = 0, output reg O_isBranch = 0, output reg [4:0] O_regD = 0, output [4:0] O_regA, output [4:0] O_regB, output reg [1:0] O_selCin = 0, output reg [2:0] O_selMem = 0, output reg [2:0] O_branchOp = 0, output reg [1:0] O_selWb = 0, output reg useRegB = 0, output reg O_memE = 0, output reg O_memWe = 0, output reg interrupts_enabled = 1, output reg [13:0] O_PC = 0, output reg [13:0] O_branchTarget = 0 ); reg [15:0] imm_hi = 0; // contains the immidiate from seti instruction reg imm_valid = 0; // indicates wether the immidiate is valid reg [31:0] immidiate = 0; reg [31:0] dataA, dataB; reg [13:0] branchAddress; reg [4:0] regD; reg [3:0] aluop; reg [2:0] branchOp, selMem; reg [1:0] selWb, selCin; reg we, isBranch, memE, memWe, set_imm_valid, enable_interrupts; assign O_regA = `rega_sel; assign O_regB = `regb_sel; always @* begin casez (`opcode) `STORE,`BRANCH : immidiate[15:0] = {`regd, I_instruction[10:0]}; default : immidiate[15:0] = `imm_value; endcase immidiate[31:16] = imm_valid ? imm_hi : {16{immidiate[15]}}; enable_interrupts = 0; dataA = I_regA; dataB = I_regB; aluop = `ALU_ADD; useRegB = !`IMM_bit; regD = `regd; we = 1 && (`regd != 5'h0); set_imm_valid = 0; isBranch = 0; branchAddress = 13'dx; selCin = 2'bxx; selMem = 2'bxx; memE = 0; memWe = 0; branchOp = `branch_condition; selWb = 0; $display("----------------------------------\ndecode instruction: instruction %h",I_instruction); casez (`opcode) `ADD: begin selCin = `C_bit ? 2'd1 : 2'd0; dataB = `IMM_bit ? immidiate : I_regB; end `SUB: begin selCin = `C_bit ? 2'd2 : 2'd3; dataA = ~ I_regA; dataB = `IMM_bit ? immidiate : I_regB; end `LOGIC_OR: begin aluop = `ALU_OR; dataB = `IMM_bit ? immidiate : I_regB; end `LOGIC_AND: begin aluop = `ALU_AND; dataB = `IMM_bit ? immidiate : I_regB; end `LOGIC_XOR: begin aluop = `ALU_XOR; dataB = `IMM_bit ? immidiate : I_regB; end `SEXT: begin aluop = `SE_bit ? `ALU_SEXT16 : `ALU_SEXT8; end `SHF: begin case (`SHF_bits) 0: aluop = `ALU_SHL; 1: aluop = `ALU_SHR; 2: aluop = `ALU_SAR; 3: aluop = `ALU_SHL; endcase dataB = `IMM_bit ? immidiate : I_regB; end `MUL: begin aluop = `ALU_MUL; dataB = `IMM_bit ? immidiate : I_regB; $display("mul c%d = %d * %d, rega %d, regb %d", `regd, O_dataA, O_dataB, `rega_sel, `regb_sel); end `IMM: begin useRegB = 0; we = 0; set_imm_valid = 1; end `EINT: begin we = 0; useRegB = 0; end `LOAD: begin useRegB = 0; selWb = 1; memE = 1; memWe = 0; selMem = I_instruction[28:26]; dataB = immidiate; end `STORE: begin useRegB = 0; memE = 1; memWe = 1; selMem = I_instruction[27:26]; we = 0; dataB = immidiate; end `BRANCH: begin regD = `rega_sel; isBranch = 1; we = `LINK_bit ? 1'b1 : 1'b0; if (`LINK_bit) begin selWb = 2; end if (I_instruction[1] && (I_instruction[28:26] == 3'b111)) begin branchAddress = I_regA[15:2]; end else begin branchAddress = immidiate[15:2]; useRegB = 1; end if (I_instruction[1] && (O_regA == 17)) begin enable_interrupts = 1; end $display("Branch: branch_addr %h, link bit %b", branchAddress, `LINK_bit); end default: begin $display("Error invalid opcode at PC:%h", O_PC); we = 0; end endcase end always @(posedge I_clk) begin imm_hi <= `imm_value; if (I_rst || I_flush) begin imm_valid <= 0; O_we <= 0; O_memE <= 0; O_isBranch <= 0; $display("bubble or branch O_PC = %h", O_PC); end else if (! I_stall ) begin if (did_interrupt) begin interrupts_enabled <= 0; end else if(`opcode == `EINT) begin interrupts_enabled <= I_instruction[0]; end else begin interrupts_enabled <= enable_interrupts ? 1 : interrupts_enabled; end O_storeData <= I_regB; O_PC <= I_PC; O_dataA <= dataA; O_dataB <= dataB; O_aluop <= aluop; O_regD <= regD; O_we <= we; imm_valid <= set_imm_valid; O_isBranch <= isBranch; O_branchTarget <= branchAddress; O_selCin <= selCin; O_selMem <= selMem; O_memE <= memE; O_memWe <= memWe; O_branchOp <= branchOp; O_selWb <= selWb; end end endmodule
#include <bits/stdc++.h> using namespace std; int n; struct node { int sig; int bz; char s[11]; int get() { int len = strlen(s); int x = 0; if (s[0] == 0 ) return 0; for (int i = 0; i < len; i++) if (s[i] < 0 || s[i] > 9 ) return 0; else x = x * 10 + s[i] - 0 ; return x; } } f[200000], g[200000], c[200000], d[200000]; int a[200000 * 4], b[200000 * 4]; int tot, m, calc, totc, totd; int ans[200000][2]; void ins(int* f, int l, int r, int s, int ll, int v) { if (l == r) { f[s] = v; return; } if ((l + r) / 2 >= ll) ins(f, l, (l + r) / 2, s + s, ll, v); else ins(f, (l + r) / 2 + 1, r, s + s + 1, ll, v); f[s] = min(f[s + s], f[s + s + 1]); } int get(int* f, int l, int r, int s) { if (l == r) { f[s] = 1; return l; } if (!f[s + s]) { int x = get(f, l, (l + r) / 2, s + s); f[s] = min(f[s + s], f[s + s + 1]); return x; } else { int x = get(f, (l + r) / 2 + 1, r, s + s + 1); f[s] = min(f[s + s], f[s + s + 1]); return x; } } void clear(int* f, int l, int r, int s, int ll) { if (l == r) { f[s] = 0; return; } if ((l + r) / 2 >= ll) clear(f, l, (l + r) / 2, s + s, ll); else clear(f, (l + r) / 2 + 1, r, s + s + 1, ll); f[s] = min(f[s + s], f[s + s + 1]); } int main() { scanf( %d , &n); for (int i = 1; i <= n; i++) { scanf( %s %d , f[i].s, &f[i].sig); f[i].bz = i; m += f[i].sig; } for (int i = 1; i <= n; i++) { int x = f[i].get(); if (x && x <= m) { ins(a, 1, m, 1, x, i); if (!f[i].sig) c[++totc] = f[i]; } else if (x && x <= n) { ins(b, 1, n - m, 1, x - m, i); if (f[i].sig) d[++totd] = f[i]; } else g[++tot] = f[i]; } int lc = 1, ld = 1, extra = n; int tot1 = tot; while (lc <= totc || ld <= totd) { if (!b[1] && lc <= totc) { ans[++calc][0] = c[lc].bz; ans[calc][1] = get(b, 1, n - m, 1) + m; clear(a, 1, m, 1, c[lc].get()); lc++; } else if (!a[1] && ld <= totd) { ans[++calc][0] = d[ld].bz; ans[calc][1] = get(a, 1, m, 1); clear(b, 1, n - m, 1, d[ld].get() - m); ld++; } else if (lc <= totc) { ans[++calc][0] = c[lc].bz; ans[calc][1] = ++extra; clear(a, 1, m, 1, c[lc].get()); g[++tot] = c[lc]; lc++; } else { ans[++calc][0] = d[ld].bz; ans[calc][1] = ++extra; clear(b, 1, n - m, 1, d[ld].get() - m); g[++tot] = d[ld]; ld++; } } for (int i = 1; i <= tot1; i++) if (g[i].sig) { ans[++calc][0] = g[i].bz; ans[calc][1] = get(a, 1, m, 1); } else { ans[++calc][0] = g[i].bz; ans[calc][1] = get(b, 1, n - m, 1) + m; } for (int i = tot; i > tot1; i--) if (g[i].sig) { ans[++calc][0] = -(extra); extra--; ans[calc][1] = get(a, 1, m, 1); } else { ans[++calc][0] = -(extra); extra--; ans[calc][1] = get(b, 1, n - m, 1) + m; } printf( %d n , calc); for (int i = 1; i <= calc; i++) if (ans[i][0] < 0) printf( move %d %d n , -ans[i][0], ans[i][1]); else printf( move %s %d n , f[ans[i][0]].s, ans[i][1]); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int n, arr[100]; cin >> n; for (int i = 0; i < n; i++) { cin >> arr[i]; } for (int i = 0; i < n - 1; i++) { for (int j = i; j < n; j++) { if (arr[i] > arr[j]) { int swap = arr[j]; arr[j] = arr[i]; arr[i] = swap; } } } for (int i = 0; i < n; i++) { cout << arr[i] << endl; } return 0; }
//----------------------------------------------------------------- // FPGA Audio Project SoC IP // V0.1 // Ultra-Embedded.com // Copyright 2011 - 2012 // // Email: // // License: LGPL // // If you would like a version with a different license for use // in commercial projects please contact the above email address // for more details. //----------------------------------------------------------------- // // Copyright (C) 2011 - 2012 Ultra-Embedded.com // // This source file may be used and distributed without // restriction provided that this copyright statement is not // removed from the file and that any derivative work contains // the original copyright notice and the associated disclaimer. // // This source file is free software; you can redistribute it // and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any // later version. // // This source is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU Lesser General Public License for more // details. // // You should have received a copy of the GNU Lesser General // Public License along with this source; if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, // Boston, MA 02111-1307 USA //----------------------------------------------------------------- //----------------------------------------------------------------- // Module: //----------------------------------------------------------------- module uart ( // Clock & Reset clk_i, rst_i, // Status tx_busy_o, rx_ready_o, // Data data_i, wr_i, data_o, rd_i, // UART pins rxd_i, txd_o ); //----------------------------------------------------------------- // Params //----------------------------------------------------------------- parameter [31:0] UART_DIVISOR = 278; //----------------------------------------------------------------- // I/O //----------------------------------------------------------------- input clk_i /*verilator public*/; input rst_i /*verilator public*/; input [7:0] data_i /*verilator public*/; output [7:0] data_o /*verilator public*/; input wr_i /*verilator public*/; input rd_i /*verilator public*/; output tx_busy_o /*verilator public*/; output rx_ready_o /*verilator public*/; input rxd_i /*verilator public*/; output txd_o /*verilator public*/; //----------------------------------------------------------------- // Registers //----------------------------------------------------------------- parameter FULL_BIT = UART_DIVISOR; parameter HALF_BIT = (FULL_BIT / 2); // TX Signals reg [7:0] tx_buf; reg tx_buf_full; reg tx_busy; reg [3:0] tx_bits; integer tx_count; reg [7:0] tx_shift_reg; reg txd_o; // RX Signals reg i_rxd; reg [7:0] data_o; reg [3:0] rx_bits; integer rx_count; reg [7:0] rx_shift_reg; reg rx_ready_o; //----------------------------------------------------------------- // Re-sync RXD //----------------------------------------------------------------- always @ (posedge rst_i or posedge clk_i ) begin if (rst_i == 1'b1) i_rxd <= 1'b1; else i_rxd <= rxd_i; end //----------------------------------------------------------------- // RX Process //----------------------------------------------------------------- always @ (posedge clk_i or posedge rst_i ) begin if (rst_i == 1'b1) begin rx_bits <= 0; rx_count <= 0; rx_ready_o <= 1'b0; rx_shift_reg <= 8'h00; data_o <= 8'h00; end else begin // If reading data, reset data ready state if (rd_i == 1'b1) rx_ready_o <= 1'b0; // Rx bit timer if (rx_count != 0) rx_count <= (rx_count - 1); else begin //------------------------------- // Start bit detection //------------------------------- if (rx_bits == 0) begin // If RXD low, check again in half bit time if (i_rxd == 1'b0) begin rx_count <= HALF_BIT; rx_bits <= 1; end end //------------------------------- // Start bit (mid bit time point) //------------------------------- else if (rx_bits == 1) begin // RXD should still be low at mid point of bit period if (i_rxd == 1'b0) begin rx_count <= FULL_BIT; rx_bits <= (rx_bits + 1); rx_shift_reg <= 8'h00; end // Start bit not still low, reset RX process else begin rx_bits <= 0; end end //------------------------------- // Stop bit //------------------------------- else if (rx_bits == 10) begin // RXD should be still high if (i_rxd == 1'b1) begin rx_count <= 0; rx_bits <= 0; data_o <= rx_shift_reg; rx_ready_o <= 1'b1; end // Bad Stop bit - wait for a full bit period // before allowing start bit detection again else begin rx_count <= FULL_BIT; rx_bits <= 0; end end //------------------------------- // Data bits //------------------------------- else begin // Receive data LSB first rx_shift_reg[7] <= i_rxd; rx_shift_reg[6:0]<= rx_shift_reg[7:1]; rx_count <= FULL_BIT; rx_bits <= (rx_bits + 1); end end end end //----------------------------------------------------------------- // TX Process //----------------------------------------------------------------- always @ (posedge clk_i or posedge rst_i ) begin if (rst_i == 1'b1) begin tx_count <= 0; tx_bits <= 0; tx_busy <= 1'b0; txd_o <= 1'b1; tx_shift_reg <= 8'h00; tx_buf <= 8'h00; tx_buf_full <= 1'b0; end else begin // Buffer data to transmit if (wr_i == 1'b1) begin tx_buf <= data_i; tx_buf_full <= 1'b1; end // Tx bit timer if (tx_count != 0) tx_count <= (tx_count - 1); else begin //------------------------------- // Start bit (TXD = L) //------------------------------- if (tx_bits == 0) begin tx_busy <= 1'b0; // Data in buffer ready to transmit? if (tx_buf_full == 1'b1) begin tx_shift_reg <= tx_buf; tx_busy <= 1'b1; txd_o <= 1'b0; tx_buf_full <= 1'b0; tx_bits <= 1; tx_count <= FULL_BIT; end end //------------------------------- // Stop bit (TXD = H) //------------------------------- else if (tx_bits == 9) begin txd_o <= 1'b1; tx_bits <= 0; tx_count <= FULL_BIT; end //------------------------------- // Data bits //------------------------------- else begin // Shift data out LSB first txd_o <= tx_shift_reg[0]; tx_shift_reg[6:0]<= tx_shift_reg[7:1]; tx_bits <= (tx_bits + 1); tx_count <= FULL_BIT; end end end end //----------------------------------------------------------------- // Combinatorial //----------------------------------------------------------------- assign tx_busy_o = (tx_busy | tx_buf_full | wr_i); endmodule
#include <bits/stdc++.h> using LL = long long; const LL inf = 1LL << 60; const int kN = 14; int a[kN], n; int delta[kN]; int cnt[1 << kN]; LL f[1 << kN]; int decode(char c) { if (c >= 0 && c <= 9 ) return c - 0 ; return c - a + 10; } char encode(int x) { if (x < 10) return x + 0 ; return x - 10 + a ; } LL solve() { for (int mask = 1; mask < 1 << n; ++mask) { int p = __builtin_popcount((mask & -mask) - 1); cnt[mask] = cnt[mask ^ 1 << p] - delta[p]; f[mask] = inf; if (cnt[mask] < 0 || cnt[mask] >= 16) continue; for (int i = 0; i < n; ++i) if (mask >> i & 1) { int q = cnt[mask ^ 1 << i]; if (q < 0 || q >= 16) continue; f[mask] = std::min(f[mask], f[mask ^ 1 << i] + (cnt[mask] * 1LL << 4 * i)); } } return f[(1 << n) - 1]; } int main() { char str[15]; scanf( %s , str); n = strlen(str); for (int i = 0; i < n; ++i) a[i] = decode(str[n - 1 - i]); LL result = inf; for (int mask = 0; mask < 1 << n - 1; ++mask) { bool ok = true; int sum = 0; for (int i = 0; i < n; ++i) { int d = a[i]; if (mask >> i & 1) d -= 16; if (i && (mask >> i - 1 & 1)) d += 1; ok &= -16 < d && d < 16; sum += d; delta[i] = d; } if (ok && sum == 0) result = std::min(result, solve()); } if (result == inf) puts( NO ); else { for (int i = n - 1; i >= 0; --i) putchar(encode(result >> 4 * i & 15)); puts( ); } }
///////////////////////////////////////////////////////////////////////// // Copyright (c) 2008 Xilinx, Inc. All rights reserved. // // XILINX CONFIDENTIAL PROPERTY // This document contains proprietary information which is // protected by copyright. All rights are reserved. This notice // refers to original work by Xilinx, Inc. which may be derivitive // of other work distributed under license of the authors. In the // case of derivitive work, nothing in this notice overrides the // original author's license agreeement. Where applicable, the // original license agreement is included in it's original // unmodified form immediately below this header. // // Xilinx, Inc. // XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A // COURTESY TO YOU. BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS // ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE, APPLICATION OR // STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION // IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE // FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION. // XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO // THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO // ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE // FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. // ///////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// //// //// //// OR1200's DC RAMs //// //// //// //// This file is part of the OpenRISC 1200 project //// //// http://www.opencores.org/cores/or1k/ //// //// //// //// Description //// //// Instatiation of DC RAM blocks. //// //// //// //// To Do: //// //// - make it smaller and faster //// //// //// //// Author(s): //// //// - Damjan Lampret, //// //// //// ////////////////////////////////////////////////////////////////////// //// //// //// Copyright (C) 2000 Authors and OPENCORES.ORG //// //// //// //// This source file may be used and distributed without //// //// restriction provided that this copyright statement is not //// //// removed from the file and that any derivative work contains //// //// the original copyright notice and the associated disclaimer. //// //// //// //// This source file is free software; you can redistribute it //// //// and/or modify it under the terms of the GNU Lesser General //// //// Public License as published by the Free Software Foundation; //// //// either version 2.1 of the License, or (at your option) any //// //// later version. //// //// //// //// This source is distributed in the hope that it will be //// //// useful, but WITHOUT ANY WARRANTY; without even the implied //// //// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR //// //// PURPOSE. See the GNU Lesser General Public License for more //// //// details. //// //// //// //// You should have received a copy of the GNU Lesser General //// //// Public License along with this source; if not, download it //// //// from http://www.opencores.org/lgpl.shtml //// //// //// ////////////////////////////////////////////////////////////////////// // // CVS Revision History // // $Log: or1200_dc_ram.v,v $ // Revision 1.1 2008/05/07 22:43:21 daughtry // Initial Demo RTL check-in // // Revision 1.6 2004/06/08 18:17:36 lampret // Non-functional changes. Coding style fixes. // // Revision 1.5 2004/04/05 08:29:57 lampret // Merged branch_qmem into main tree. // // Revision 1.2.4.2 2003/12/10 15:28:28 simons // Support for ram with byte selects added. // // Revision 1.2.4.1 2003/12/09 11:46:48 simons // Mbist nameing changed, Artisan ram instance signal names fixed, some synthesis waning fixed. // // Revision 1.2 2002/10/17 20:04:40 lampret // Added BIST scan. Special VS RAMs need to be used to implement BIST. // // Revision 1.1 2002/01/03 08:16:15 lampret // New prefixes for RTL files, prefixed module names. Updated cache controllers and MMUs. // // Revision 1.8 2001/10/21 17:57:16 lampret // Removed params from generic_XX.v. Added translate_off/on in sprs.v and id.v. Removed spr_addr from dc.v and ic.v. Fixed CR+LF. // // Revision 1.7 2001/10/14 13:12:09 lampret // MP3 version. // // Revision 1.1.1.1 2001/10/06 10:18:36 igorm // no message // // Revision 1.2 2001/08/09 13:39:33 lampret // Major clean-up. // // Revision 1.1 2001/07/20 00:46:03 lampret // Development version of RTL. Libraries are missing. // // // synopsys translate_off `include "timescale.v" // synopsys translate_on `include "or1200_defines.v" module or1200_dc_ram( // Reset and clock clk, rst, `ifdef OR1200_BIST // RAM BIST mbist_si_i, mbist_so_o, mbist_ctrl_i, `endif // Internal i/f addr, en, we, datain, dataout ); parameter dw = `OR1200_OPERAND_WIDTH; parameter aw = `OR1200_DCINDX; // // I/O // input clk; input rst; input [aw-1:0] addr; input en; input [3:0] we; input [dw-1:0] datain; output [dw-1:0] dataout; `ifdef OR1200_BIST // // RAM BIST // input mbist_si_i; input [`OR1200_MBIST_CTRL_WIDTH - 1:0] mbist_ctrl_i; // bist chain shift control output mbist_so_o; `endif `ifdef OR1200_NO_DC // // Data cache not implemented // assign dataout = {dw{1'b0}}; `ifdef OR1200_BIST assign mbist_so_o = mbist_si_i; `endif `else // // Instantiation of RAM block // `ifdef OR1200_DC_1W_4KB or1200_spram_1024x32_bw dc_ram( `endif `ifdef OR1200_DC_1W_8KB or1200_spram_2048x32_bw dc_ram( `endif `ifdef OR1200_BIST // RAM BIST .mbist_si_i(mbist_si_i), .mbist_so_o(mbist_so_o), .mbist_ctrl_i(mbist_ctrl_i), `endif .clk(clk), .rst(rst), .ce(en), .we(we), .oe(1'b1), .addr(addr), .di(datain), .doq(dataout) ); `endif endmodule
module bsg_rp_clk_gen_coarse_delay_tuner ( input i , input [1:0] sel_i , input we_i , input async_reset_neg_i , output o , output we_o ); wire [1:0] sel_r; wire [7:0] signal; wire [1:0] mux_lo; // synopsys rp_group (bsg_clk_gen_cde) // synopsys rp_fill (0 0 RX) SC7P5T_CKINVX2_SSC14SL I1 ( .CLK(i) , .Z(signal[0]) ); SC7P5T_CKINVX2_SSC14SL I2 ( .CLK(signal[0]), .Z(signal[1]) ); SC7P5T_CKINVX10_SSC14SL I2a ( .CLK(signal[1]), .Z() ); SC7P5T_CKINVX2_SSC14SL I3 ( .CLK(signal[1]), .Z(signal[2]) ); SC7P5T_CKINVX2_SSC14SL I4 ( .CLK(signal[2]), .Z(signal[3]) ); SC7P5T_CKINVX10_SSC14SL I4a ( .CLK(signal[3]), .Z() ); SC7P5T_CKINVX2_SSC14SL I5 ( .CLK(signal[3]), .Z(signal[4]) ); SC7P5T_CKINVX2_SSC14SL I6 ( .CLK(signal[4]), .Z(signal[5]) ); SC7P5T_CKINVX10_SSC14SL I6a ( .CLK(signal[5]), .Z() ); SC7P5T_CKINVX2_SSC14SL I7 ( .CLK(signal[5]), .Z(signal[6]) ); SC7P5T_CKINVX2_SSC14SL I8 ( .CLK(signal[6]), .Z(signal[7]) ); // synopsys rp_fill (0 1 RX) SC7P5T_MUXI4X4_SSC14SL M1 ( .D0(signal[5]), .D1(signal[3]), .D2(signal[1]), .D3(i), .S0(sel_r[0]), .S1(sel_r[1]), .Z(o) ); // synopsys rp_fill (0 2 RX) SC7P5T_DFFNRQX4_SSC14SL sel_r_reg_0 ( .D(mux_lo[0]), .CLK(o), .RESET(async_reset_neg_i), .Q(sel_r[0]) ); SC7P5T_MUX2X1_SSC14SL MX1 ( .D0(sel_r[0]), .D1(sel_i[0]), .S(we_i), .Z(mux_lo[0]) ); // synopsys rp_fill (0 3 RX) SC7P5T_DFFNRQX4_SSC14SL sel_r_reg_1 ( .D(mux_lo[1]), .CLK(o), .RESET(async_reset_neg_i), .Q(sel_r[1]) ); SC7P5T_MUX2X1_SSC14SL MX2 ( .D0(sel_r[1]),.D1(sel_i[1]),.S(we_i), .Z(mux_lo[1]) ); // synopsys rp_fill (0 4 RX) SC7P5T_BUFX4_SSC14SL we_o_buf ( .A(we_i), .Z(we_o) ); // synopsys rp_endgroup (bsg_clk_gen_cde) endmodule `BSG_ABSTRACT_MODULE(bsg_rp_clk_gen_coarse_delay_tuner)
#include <bits/stdc++.h> using namespace std; const int node_max = 3000; struct network { struct node { int v, c, w, b; node(int _v = 0, int _c = 0, int _w = 0, int _b = 0) : v(_v), c(_c), w(_w), b(_b) {} }; int n, pre[node_max]; vector<node> nd[node_max]; void clear() { for (int i = 0; i < n; ++i) nd[i].clear(); n = 0; } void insert(int u, int v, int c, int w, bool d = false) { n = max(n, max(u, v) + 1); nd[u].push_back(node(v, c, w, nd[v].size())); nd[v].push_back(node(u, 0, -w, nd[u].size() - 1)); if (d) { nd[v].push_back(node(u, c, w, nd[u].size())); nd[u].push_back(node(v, 0, -w, nd[v].size() - 1)); } } pair<int, int> get_max_flow_min_cost(int src, int dst) { pair<int, int> res; int flow; while ((flow = get_min_path(src, dst)) != 0) { res.first += flow; for (int i = dst; i != src; i = nd[i][pre[i]].v) { res.second += nd[nd[i][pre[i]].v][nd[i][pre[i]].b].w * flow; nd[nd[i][pre[i]].v][nd[i][pre[i]].b].c -= flow; nd[i][pre[i]].c += flow; } } return res; } int get_min_path(int src, int dst) { int dis[node_max], bfs[node_max]; bool visited[node_max] = {}; fill(dis, dis + n, INT_MAX); visited[src] = true; dis[src] = 0; bfs[0] = src; for (int s = 0, t = 1; s != t; visited[bfs[s]] = 0, s = (s + 1) % n) { int v = bfs[s]; for (vector<node>::iterator i = nd[v].begin(); i != nd[v].end(); ++i) { if (i->c <= 0 || dis[v] + i->w >= dis[i->v]) continue; dis[i->v] = dis[v] + i->w; pre[i->v] = i->b; if (!visited[i->v]) { visited[i->v] = true; bfs[t] = i->v; t = (t + 1) % n; } } } if (dis[dst] == INT_MAX) return 0; int res = INT_MAX; for (int i = dst; i != src; i = nd[i][pre[i]].v) res = min(res, nd[nd[i][pre[i]].v][nd[i][pre[i]].b].c); return res; } }; int n, m, s[1024], t[1024], c[1024], ans[1024]; network g; bool solve() { if (scanf( %d%d , &n, &m) == EOF) return false; for (int i = 0; i < n; ++i) scanf( %d%d%d , &s[i], &t[i], &c[i]); g.clear(); int S = n * 2, T = n * 2 + 2; g.insert(S, S + 1, m, 0); for (int i = 0; i < n; ++i) { g.insert(S + 1, i, 1, 0); g.insert(i + n, T, 1, 0); g.insert(i, i + n, 1, -c[i]); for (int j = 0; j < n; ++j) { if (i != j && s[i] + t[i] <= s[j]) { g.insert(i + n, j, 1, 0); } } } g.get_max_flow_min_cost(S, T); for (int i = 0; i < n; ++i) { ans[i] = 0; for (vector<network::node>::iterator j = g.nd[i].begin(); j != g.nd[i].end(); ++j) { if (j->v == i + n && j->c == 0) { ans[i] = 1; } } printf(i == n - 1 ? %d n : %d , ans[i]); } return true; } int main() { while (solve()) ; return 0; }
// ============================================================================ // Copyright (c) 2010 // ============================================================================ // // Permission: // // // // Disclaimer: // // This VHDL/Verilog or C/C++ source code is intended as a design reference // which illustrates how these types of functions can be implemented. // It is the user's responsibility to verify their design for // consistency and functionality through the use of formal // verification methods. // ============================================================================ // // ReConfigurable Computing Group // // web: http://www.ecs.umass.edu/ece/tessier/rcg/ // // // ============================================================================ // Major Functions/Design Description: // // // // ============================================================================ // Revision History: // ============================================================================ // Ver.: |Author: |Mod. Date: |Changes Made: // V1.0 |RCG |05/10/2011 | // ============================================================================ //include "NF_2.1_defines.v" //include "registers.v" //include "reg_defines_reference_router.v" `timescale 1ns/1ps module ip_checksum_ttl #(parameter DATA_WIDTH = 64) ( //--- datapath interface input [DATA_WIDTH-1:0] in_data, input in_wr, //--- interface to preprocess input word_ETH_IP_VER, input word_IP_LEN_ID, input word_IP_FRAG_TTL_PROTO, input word_IP_CHECKSUM_SRC_HI, input word_IP_SRC_DST, input word_IP_DST_LO, // --- interface to process output ip_checksum_vld, output ip_checksum_is_good, output ip_hdr_has_options, output ip_ttl_is_good, output [7:0] ip_new_ttl, output [15:0] ip_new_checksum, // new checksum assuming decremented TTL input rd_checksum, // misc input reset, input clk ); //---------------------- Wires and regs--------------------------- reg [19:0] checksum_word_0, checksum_word_1; reg [19:0] in_word_0_0, in_word_0_1, in_word_0_2; reg [19:0] in_word_1_0, in_word_1_1, in_word_1_2; wire [19:0] next_sum_0, next_sum_1; reg [16:0] adjusted_checksum; reg checksum_done; wire empty; reg [7:0] ttl_new; reg ttl_good; reg hdr_has_options; reg add_carry_1, add_carry_2; //------------------------- Modules------------------------------- fallthrough_small_fifo #(.WIDTH(27), .MAX_DEPTH_BITS(2)) arp_fifo (.din ({&checksum_word_0[15:0], adjusted_checksum[15:0], ttl_good, ttl_new, hdr_has_options}), // {IP good, new checksum} .wr_en (checksum_done), // Write enable .rd_en (rd_checksum), // Read the next word .dout ({ip_checksum_is_good, ip_new_checksum, ip_ttl_is_good, ip_new_ttl, ip_hdr_has_options}), .full (), .nearly_full (), .prog_full (), .empty (empty), .reset (reset), .clk (clk) ); //------------------------- Logic ------------------------------- assign ip_checksum_vld = !empty; /* MUX the additions to save adder logic */ assign next_sum_0 = in_word_0_0 + in_word_0_1 + in_word_0_2; assign next_sum_1 = in_word_1_0 + in_word_1_1 + in_word_1_2; always @(*) begin in_word_0_0 = {4'h0, in_data[31:16]}; in_word_0_1 = {4'h0, in_data[15:0]}; in_word_0_2 = checksum_word_0; in_word_1_0 = {4'h0, in_data[DATA_WIDTH-1:DATA_WIDTH-16]}; in_word_1_1 = {4'h0, in_data[DATA_WIDTH-17:DATA_WIDTH-32]}; in_word_1_2 = checksum_word_1; if(word_ETH_IP_VER) begin in_word_0_0 = 20'h0; in_word_0_2 = 20'h0; end if(word_IP_DST_LO) begin in_word_0_0 = {4'h0, in_data[DATA_WIDTH-1:DATA_WIDTH-16]}; in_word_0_1 = checksum_word_1; end if(add_carry_1 | add_carry_2) begin in_word_0_0 = 20'h0; in_word_0_1 = {16'h0, checksum_word_0[19:16]}; in_word_0_2 = {4'h0, checksum_word_0[15:0]}; end if(word_IP_LEN_ID) begin in_word_1_2 = 20'h0; end end // always @ (*) // checksum logic. 16bit 1's complement over the IP header. // --- see RFC1936 for guidance. // 1's compl add: do a 2's compl add and then add the carry out // as if it were a carry in. // Final checksum (computed over the whole header incl checksum) // is in checksum_a and valid when IP_checksum_valid is 1 // If checksum is good then it should be 0xffff always @(posedge clk) begin if(reset) begin checksum_word_0 <= 20'h0; // does the addition for the low 32 bits checksum_word_1 <= 20'h0; // does the addition for the high 32 bits adjusted_checksum <= 17'h0; // calculates the new chksum checksum_done <= 0; add_carry_1 <= 0; add_carry_2 <= 0; ttl_new <= 0; ttl_good <= 0; hdr_has_options <= 0; end else begin /* make sure the version is correct and there are no options */ if(word_ETH_IP_VER) begin hdr_has_options <= (in_data[15:8]!=8'h45); end if(word_IP_FRAG_TTL_PROTO) begin ttl_new <= (in_data[15:8]==8'h0) ? 8'h0 : in_data[15:8] - 1'b1; ttl_good <= (in_data[15:8] > 8'h1); end if(word_ETH_IP_VER | word_IP_FRAG_TTL_PROTO | word_IP_SRC_DST | word_IP_DST_LO | add_carry_1 | add_carry_2) begin checksum_word_0 <= next_sum_0; end if(word_IP_LEN_ID | word_IP_CHECKSUM_SRC_HI) begin checksum_word_1 <= next_sum_1; end // see RFC 1141 if(word_IP_CHECKSUM_SRC_HI) begin adjusted_checksum <= {1'h0, in_data[DATA_WIDTH-1:DATA_WIDTH-16]} + 17'h0100; // adjust for the decrement in TTL end if(word_IP_DST_LO) begin adjusted_checksum <= {1'h0, adjusted_checksum[15:0]} + adjusted_checksum[16]; add_carry_1 <= 1; end else begin add_carry_1 <= 0; end if(add_carry_1) begin add_carry_2 <= 1; end else begin add_carry_2 <= 0; end if(add_carry_2) begin checksum_done <= 1; end else begin checksum_done <= 0; end // synthesis translate_off // If we have any carry left in top 4 bits then algorithm is wrong if (checksum_done && checksum_word_0[19:16] != 4'h0) begin $display("%t %m ERROR: top 4 bits of checksum_word_0 not zero - algo wrong???", $time); #100 $stop; end // synthesis translate_on end // else: !if(reset) end // always @ (posedge clk) endmodule // IP_checksum
/* * im.v - instruction memory * * Given a 32-bit address the data is latched and driven * on the rising edge of the clock. * * Currently it supports 7 address bits resulting in * 128 bytes of memory. The lowest two bits are assumed * to be byte indexes and ignored. Bits 8 down to 2 * are used to construct the address. * * The memory is initialized using the Verilog $readmemh * (read memory in hex format, ascii) operation. * The file to read from can be configured using .IM_DATA * parameter and it defaults to "im_data.txt". * The number of memory records can be specified using the * .NMEM parameter. This should be the same as the number * of lines in the file (wc -l im_data.txt). */ `ifndef _im `define _im module im( input wire clk, input wire [31:0] addr, output wire [31:0] data); parameter NMEM = 128; // Number of memory entries, // not the same as the memory size parameter IM_DATA = "im_data.txt"; // file to read data from reg [31:0] mem [0:127]; // 32-bit memory with 128 entries initial begin $readmemh(IM_DATA, mem, 0, NMEM-1); end assign data = mem[addr[8:2]][31:0]; endmodule `endif
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1); inline bool EQ(double a, double b) { return fabs(a - b) < 1e-9; } long long add(long long a, long long b) { long long ret = a + b; if (ret >= 1000000007) ret -= 1000000007; return ret; } long long subtract(long long a, long long b) { long long ret = a - b; if (ret < 0) ret += 1000000007; return ret; } long long mult(long long a, long long b) { long long ret = a * b; if (ret >= 1000000007) ret %= 1000000007; return ret; } long long bigmod(long long a, long long b) { long long ret = 1; while (b) { if (b & 1) ret = mult(ret, a); b >>= 1; a = mult(a, a); } return ret; } long long inverse(long long n) { return bigmod(n, 1000000007 - 2); } bool base[1000010]; vector<int> primes; void sieve(int mx) { mx += 10; int x = sqrt(mx); for (int i = 3; i <= x; i += 2) if (base[i] == 0) for (int j = i * i, k = i << 1; j < mx; j += k) base[j] = 1; primes.push_back(2); for (int i = 3; i < mx; i += 2) if (base[i] == 0) primes.push_back(i); } bool checkBit(int n, int i) { return (n & (1 << i)); } int setBit(int n, int i) { return (n | (1 << i)); } int resetBit(int n, int i) { return (n & (~(1 << i))); } char a[22], b[22]; int c[22]; struct node { int end; node *next[2]; node() { end = 0; next[0] = next[1] = NULL; } } * root; void insert(int val) { node *curr = root; for (int i = 0; i < 18; ++i) { int id = c[i]; if (curr->next[id] == NULL) curr->next[id] = new node; curr = curr->next[id]; } curr->end += val; } int query() { node *curr = root; for (int i = 0; i < 18; ++i) { int id = c[i]; if (curr->next[id] == NULL) return 0; curr = curr->next[id]; } return curr->end; } int main() { int q; scanf( %d , &q); root = new node; while (q--) { scanf( %s , a); scanf( %s , b); int n = strlen(b); for (int i = 0; i < 18 - n; ++i) c[i] = 0; for (int i = 0; i < n; ++i) c[18 - n + i] = ((b[i] - 0 ) & 1); if (a[0] == + ) insert(1); else if (a[0] == - ) insert(-1); else { printf( %d n , query()); } } return 0; }
#include <bits/stdc++.h> int cmp(const void *a, const void *b) { return *((int *)a) - *((int *)b); } int maximum(int a, int b) { if (a > b) { return a; } else { return b; } } int minimum(int a, int b) { if (a < b) { return a; } else { return b; } } int main() { int a[2000]; int p = 0, q = 1, x = 1, i, j; int pl, pr, vl, vr, k; long long c = 0, d; a[0] = 0; for (i = 0; i < 9; i++) { for (j = p; j < q; j++) { a[x++] = a[j] * 10 + 4; a[x++] = a[j] * 10 + 7; } p = q; q = x; } qsort(a, x, sizeof(int), cmp); a[x] = 1000000001; scanf( %d %d %d %d %d , &pl, &pr, &vl, &vr, &k); d = (long long)(pr - pl + 1) * (vr - vl + 1); for (i = 1; i <= x - k; i++) { if (pl <= a[i] && vr >= a[i + k - 1]) { int s1 = minimum(a[i], pr); int s2 = maximum(a[i - 1] + 1, pl); int t1 = maximum(a[i + k - 1], vl); int t2 = minimum(a[i + k] - 1, vr); if (s1 - s2 >= 0 && t2 - t1 >= 0) { c += (long long)(s1 - s2 + 1) * (t2 - t1 + 1); } } if (vl <= a[i] && pr >= a[i + k - 1]) { int s1 = minimum(a[i], vr); int s2 = maximum(a[i - 1] + 1, vl); int t1 = maximum(a[i + k - 1], pl); int t2 = minimum(a[i + k] - 1, pr); if (s1 - s2 >= 0 && t2 - t1 >= 0) { c += (long long)(s1 - s2 + 1) * (t2 - t1 + 1); } } } if (k == 1) { for (i = 1; i < x; i++) { if (pl <= a[i] && pr >= a[i] && vl <= a[i] && vr >= a[i]) c--; } } printf( %.20lf n , (double)c / d); return 0; }
module pipeline4_testbench(); // faz o include dos parameters das instrucoes `include "params_proc.v" // indica o numero de testes a serem feitos parameter N_TESTES = 5; // declaracao das input e output reg clk_in, RST; reg [CTRL_WIDTH-1:0] ctrl_in; reg we; reg signed [DATA_WIDTH-1:0] data; reg [MEM_WIDTH-1:0] addr; reg [REG_ADDR_WIDTH-1:0] reg_addr_in; wire signed [DATA_WIDTH-1:0] reg_data_out; wire [REG_ADDR_WIDTH-1:0] reg_addr_out; wire [CTRL_WIDTH-1:0] ctrl_out; // instancia do modulo a ser testado pipeline4 pipeline40( .clk_in(clk_in), .RST(RST), .ctrl_in(ctrl_in), .we(we), .data(data), .addr(addr), .reg_addr_in(reg_addr_in), .reg_data_out(reg_data_out), .reg_addr_out(reg_addr_out), .ctrl_out(ctrl_out) ); // inicializa os inputs do modulo (acima) a ser testado task init_input; begin ctrl_in = NOP; we = 0; data = 0; addr = 0; reg_addr_in = 0; end endtask // executa o teste numero 'testes' emitindo status como resultado do teste task execute_test; input integer testes; output reg status; // dados dos testes parameter TESTE1_DATA = 5, TESTE1_CTRL = SW, TESTE1_ADDR = 0, TESTE1_REG_ADDR = 15; parameter TESTE2_DATA = 15, TESTE2_CTRL = LW, TESTE2_ADDR = TESTE1_ADDR, TESTE2_REG_ADDR = 20; parameter TESTE3_DATA = 25, TESTE3_CTRL = ADD, TESTE3_ADDR = TESTE1_ADDR+1, TESTE3_REG_ADDR = 22; parameter TESTE4_DATA = 37, TESTE4_CTRL = SUB, TESTE4_ADDR = TESTE3_ADDR, TESTE4_REG_ADDR = 30; begin case(testes) 0: begin ctrl_in <= TESTE1_CTRL; we <= 1; data <= TESTE1_DATA; addr <= TESTE1_ADDR; reg_addr_in <= TESTE1_REG_ADDR; status <= 0; end 1: begin ctrl_in <= TESTE2_CTRL; we <= 0; data <= TESTE2_DATA; addr <= TESTE2_ADDR; reg_addr_in <= TESTE2_REG_ADDR; if (reg_data_out == TESTE1_DATA && ctrl_out == TESTE1_CTRL && reg_addr_out == TESTE1_REG_ADDR) begin status <= 0; end else begin status <= 1; end end 2: begin ctrl_in <= TESTE3_CTRL; we <= 1; data <= TESTE3_DATA; addr <= TESTE3_ADDR; reg_addr_in <= TESTE3_REG_ADDR; if (reg_data_out == TESTE1_DATA && ctrl_out == TESTE2_CTRL && reg_addr_out == TESTE2_REG_ADDR) begin status <= 0; end else begin status <= 1; end end 3: begin ctrl_in <= TESTE4_CTRL; we <= 0; data <= TESTE4_DATA; addr <= TESTE4_ADDR; reg_addr_in <= TESTE4_REG_ADDR; if (reg_data_out == TESTE3_DATA && ctrl_out == TESTE3_CTRL && reg_addr_out == TESTE3_REG_ADDR) begin status <= 0; end else begin status <= 1; end end 4: begin ctrl_in <= TESTE1_CTRL; we <= 0; data <= TESTE1_DATA; addr <= TESTE4_ADDR; reg_addr_in <= TESTE1_REG_ADDR; if (reg_data_out == TESTE3_DATA && ctrl_out == TESTE4_CTRL && reg_addr_out == TESTE4_REG_ADDR) begin status <= 0; end else begin status <= 1; end end default: begin // nenhum teste em execucao, logo status padrao e de SUCESSO status <= 0; end endcase end endtask // mostra as entradas no console task display_input; input integer testes; input reg status; begin $display(" Teste # %2d => ", testes); $display("\t ------ ENTRADAS ------- "); $display("\t WE: %b ", we); $display("\t ADDR: %6d - DATA: %6d ", addr, data); $display("\t REG_ADDR_IN: %3d ", reg_addr_in); $write( "\t CTRL: %b (", ctrl_in); case(ctrl_in) LW: $display("LW)"); LW_IMM: $display("LW_IMM)"); SW: $display("SW)"); ADD: $display("ADD)"); SUB: $display("SUB)"); MUL: $display("MUL)"); DIV: $display("DIV)"); AND: $display("AND)"); OR: $display("OR)"); NOT: $display("NOT)"); CMP: $display("CMP)"); JR: $display("JR)"); JPC: $display("JPC)"); BRFL: $display("BRFL)"); CALL: $display("CALL)"); RET: $display("RET)"); NOP: $display("NOP)"); endcase end endtask // mostra as saidas no console task display_output; input integer testes; input reg status; begin $display("\t ------ SAIDAS ------- "); $display("\t REG_DATA_OUT: %6d ", reg_data_out); $display("\t REG_ADDR_OUT: %3d ", reg_addr_out); $write( "\t CTRL_OUT: %b (", ctrl_out); case(ctrl_out) LW: $display("LW)"); LW_IMM: $display("LW_IMM)"); SW: $display("SW)"); ADD: $display("ADD)"); SUB: $display("SUB)"); MUL: $display("MUL)"); DIV: $display("DIV)"); AND: $display("AND)"); OR: $display("OR)"); NOT: $display("NOT)"); CMP: $display("CMP)"); JR: $display("JR)"); JPC: $display("JPC)"); BRFL: $display("BRFL)"); CALL: $display("CALL)"); RET: $display("RET)"); NOP: $display("NOP)"); endcase end endtask // faz o include do modelo de testbench // ESTE INCLUDE DEVE VIR POR ULTIMO !!! `include "testbench.v" endmodule
#include <bits/stdc++.h> using namespace std; const int iinf = 1 << 29; const long long inf = 1ll << 60; const long long mod = 1e9 + 7; void GG() { cout << -1 n ; exit(0); } long long mpow(long long a, long long n, long long mo = mod) { long long re = 1; while (n > 0) { if (n & 1) re = re * a % mo; a = a * a % mo; n >>= 1; } return re; } long long inv(long long b) { return b == 1 ? 1 : (mod - mod / b) * inv(mod % b) % mod; } const int maxn = 2e5 + 5; int p[maxn][26]; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); ; string second; cin >> second; int n = second.length(); for (int i = (0); i < (n); ++i) { for (int j = (0); j < (26); ++j) p[i + 1][j] += p[i][j]; p[i + 1][second[i] - a ]++; } int q; cin >> q; while (q--) { int l, r; cin >> l >> r; --l; --r; if (l == r) { cout << Yes << n ; } else { if (second[l] != second[r]) { cout << Yes << n ; } else { int tp = 0; for (int j = (0); j < (26); ++j) { if (p[r + 1][j] - p[l][j] > 0) tp++; }; if (tp > 2) cout << Yes << n ; else cout << No << n ; } } } }
/* * Copyright (c) 2002 Stephen Williams () * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ /* * Here we have the canonical "Hello, World" program written in Verilog, * with VPI. It uses the hello_vpi.vpi module that is compiled from * the hello_vpi.c program also in this directory. See the * hello_vpi.c for instructions on how to compile it. * * Compile this program with the command: * * iverilog -ohello_vpi hello_vpi.vl * * After churning for a little while, the program will create the output * file "hello" which is compiled, linked and ready to run. Run this * program like so: * * vvp -M. -mhello_vpi hello_vpi * * and the program will print the message to its output. Easy! For * more on how to make the iverilog command work, see the iverilog * manual page. */ module main(); initial begin $my_hello; $finish ; end endmodule
//Legal Notice: (C)2011 Altera Corporation. All rights reserved. Your //use of Altera Corporation's design tools, logic functions and other //software and tools, and its AMPP partner logic functions, and any //output files any of the foregoing (including device programming or //simulation files), and any associated documentation or information are //expressly subject to the terms and conditions of the Altera Program //License Subscription Agreement or other applicable license agreement, //including, without limitation, that your use is for the sole purpose //of programming logic devices manufactured by Altera and sold by Altera //or its authorized distributors. Please refer to the applicable //agreement for further details. // synthesis translate_off `timescale 1ns / 1ps // synthesis translate_on // turn off superfluous verilog processor warnings // altera message_level Level1 // altera message_off 10034 10035 10036 10037 10230 10240 10030 module ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_wrapper ( // inputs: MonDReg, break_readreg, clk, dbrk_hit0_latch, dbrk_hit1_latch, dbrk_hit2_latch, dbrk_hit3_latch, debugack, monitor_error, monitor_ready, reset_n, resetlatch, tracemem_on, tracemem_trcdata, tracemem_tw, trc_im_addr, trc_on, trc_wrap, trigbrktype, trigger_state_1, // outputs: jdo, jrst_n, st_ready_test_idle, take_action_break_a, take_action_break_b, take_action_break_c, take_action_ocimem_a, take_action_ocimem_b, take_action_tracectrl, take_action_tracemem_a, take_action_tracemem_b, take_no_action_break_a, take_no_action_break_b, take_no_action_break_c, take_no_action_ocimem_a, take_no_action_tracemem_a ) ; output [ 37: 0] jdo; output jrst_n; output st_ready_test_idle; output take_action_break_a; output take_action_break_b; output take_action_break_c; output take_action_ocimem_a; output take_action_ocimem_b; output take_action_tracectrl; output take_action_tracemem_a; output take_action_tracemem_b; output take_no_action_break_a; output take_no_action_break_b; output take_no_action_break_c; output take_no_action_ocimem_a; output take_no_action_tracemem_a; input [ 31: 0] MonDReg; input [ 31: 0] break_readreg; input clk; input dbrk_hit0_latch; input dbrk_hit1_latch; input dbrk_hit2_latch; input dbrk_hit3_latch; input debugack; input monitor_error; input monitor_ready; input reset_n; input resetlatch; input tracemem_on; input [ 35: 0] tracemem_trcdata; input tracemem_tw; input [ 6: 0] trc_im_addr; input trc_on; input trc_wrap; input trigbrktype; input trigger_state_1; wire [ 37: 0] jdo; wire jrst_n; wire [ 37: 0] sr; wire st_ready_test_idle; wire take_action_break_a; wire take_action_break_b; wire take_action_break_c; wire take_action_ocimem_a; wire take_action_ocimem_b; wire take_action_tracectrl; wire take_action_tracemem_a; wire take_action_tracemem_b; wire take_no_action_break_a; wire take_no_action_break_b; wire take_no_action_break_c; wire take_no_action_ocimem_a; wire take_no_action_tracemem_a; wire vji_cdr; wire [ 1: 0] vji_ir_in; wire [ 1: 0] vji_ir_out; wire vji_rti; wire vji_sdr; wire vji_tck; wire vji_tdi; wire vji_tdo; wire vji_udr; wire vji_uir; //Change the sld_virtual_jtag_basic's defparams to //switch between a regular Nios II or an internally embedded Nios II. //For a regular Nios II, sld_mfg_id = 70, sld_type_id = 34. //For an internally embedded Nios II, slf_mfg_id = 110, sld_type_id = 135. ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_tck the_ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_tck ( .MonDReg (MonDReg), .break_readreg (break_readreg), .dbrk_hit0_latch (dbrk_hit0_latch), .dbrk_hit1_latch (dbrk_hit1_latch), .dbrk_hit2_latch (dbrk_hit2_latch), .dbrk_hit3_latch (dbrk_hit3_latch), .debugack (debugack), .ir_in (vji_ir_in), .ir_out (vji_ir_out), .jrst_n (jrst_n), .jtag_state_rti (vji_rti), .monitor_error (monitor_error), .monitor_ready (monitor_ready), .reset_n (reset_n), .resetlatch (resetlatch), .sr (sr), .st_ready_test_idle (st_ready_test_idle), .tck (vji_tck), .tdi (vji_tdi), .tdo (vji_tdo), .tracemem_on (tracemem_on), .tracemem_trcdata (tracemem_trcdata), .tracemem_tw (tracemem_tw), .trc_im_addr (trc_im_addr), .trc_on (trc_on), .trc_wrap (trc_wrap), .trigbrktype (trigbrktype), .trigger_state_1 (trigger_state_1), .vs_cdr (vji_cdr), .vs_sdr (vji_sdr), .vs_uir (vji_uir) ); ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_sysclk the_ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_sysclk ( .clk (clk), .ir_in (vji_ir_in), .jdo (jdo), .sr (sr), .take_action_break_a (take_action_break_a), .take_action_break_b (take_action_break_b), .take_action_break_c (take_action_break_c), .take_action_ocimem_a (take_action_ocimem_a), .take_action_ocimem_b (take_action_ocimem_b), .take_action_tracectrl (take_action_tracectrl), .take_action_tracemem_a (take_action_tracemem_a), .take_action_tracemem_b (take_action_tracemem_b), .take_no_action_break_a (take_no_action_break_a), .take_no_action_break_b (take_no_action_break_b), .take_no_action_break_c (take_no_action_break_c), .take_no_action_ocimem_a (take_no_action_ocimem_a), .take_no_action_tracemem_a (take_no_action_tracemem_a), .vs_udr (vji_udr), .vs_uir (vji_uir) ); //synthesis translate_off //////////////// SIMULATION-ONLY CONTENTS assign vji_tck = 1'b0; assign vji_tdi = 1'b0; assign vji_sdr = 1'b0; assign vji_cdr = 1'b0; assign vji_rti = 1'b0; assign vji_uir = 1'b0; assign vji_udr = 1'b0; assign vji_ir_in = 2'b0; //////////////// END SIMULATION-ONLY CONTENTS //synthesis translate_on //synthesis read_comments_as_HDL on // sld_virtual_jtag_basic ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy // ( // .ir_in (vji_ir_in), // .ir_out (vji_ir_out), // .jtag_state_rti (vji_rti), // .tck (vji_tck), // .tdi (vji_tdi), // .tdo (vji_tdo), // .virtual_state_cdr (vji_cdr), // .virtual_state_sdr (vji_sdr), // .virtual_state_udr (vji_udr), // .virtual_state_uir (vji_uir) // ); // // defparam ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_auto_instance_index = "YES", // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_instance_index = 0, // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_ir_width = 2, // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_mfg_id = 110, // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_sim_action = "", // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_sim_n_scan = 0, // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_sim_total_length = 0, // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_type_id = 135, // ddr3_s4_uniphy_example_if0_p0_qsys_sequencer_cpu_inst_jtag_debug_module_phy.sld_version = 3; // //synthesis read_comments_as_HDL off endmodule
#include <bits/stdc++.h> using namespace std; const int siz = 1000000 + 10; char a[siz]; int main() { int t, n, m = 0, i, l, k; scanf( %d , &t); scanf( %s , a); int len = strlen(a); int z = 0, o = 0; for (l = 0; l < len; l++) { if (a[l] == 1 ) o++; else if (a[l] == 0 ) z++; } m = min(o, z); len -= (2 * m); printf( %d , len); return 0; }
#include <bits/stdc++.h> #pragma comment(linker, /STACK:16777216 ) using namespace std; const double pi = acos(-1.0); const int inf = (int)1e9; const double eps = 1e-4; const int ss = (int)1e6 + 3; const int base = inf; bool pred(const pair<int, int>& i, const pair<int, int>& j) { if (i.first == j.first) { return i.second > j.second; } else { return i.first > j.first; } } int a[2000005]; int main() { int k; scanf( %d , &k); long long int res = 0; for (int i = 0; i < k; ++i) { scanf( %d , &a[i]); res += a[i]; } if (k == 1) { cout << res; return 0; } sort(a, a + k); int z = k / 4; while (z != 0) { for (int i = k - 1; i >= k - z; --i) { res += a[i]; } z /= 4; } cout << res; return 0; }
/* * PicoSoC - A simple example SoC using PicoRV32 * * Copyright (C) 2017 Clifford Wolf <> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ module simpleuart ( input clk, input resetn, output ser_tx, input ser_rx, input [ 3:0] reg_div_we, input [31:0] reg_div_di, output [31:0] reg_div_do, input reg_dat_we, input reg_dat_re, input [31:0] reg_dat_di, output [31:0] reg_dat_do, output reg_dat_wait ); reg [31:0] cfg_divider; reg [3:0] recv_state; reg [31:0] recv_divcnt; reg [7:0] recv_pattern; reg [7:0] recv_buf_data; reg recv_buf_valid; reg [9:0] send_pattern; reg [3:0] send_bitcnt; reg [31:0] send_divcnt; reg send_dummy; assign reg_div_do = cfg_divider; assign reg_dat_wait = reg_dat_we && (send_bitcnt || send_dummy); assign reg_dat_do = recv_buf_valid ? recv_buf_data : ~0; always @(posedge clk) begin if (!resetn) begin cfg_divider <= 1; end else begin if (reg_div_we[0]) cfg_divider[7:0] <= reg_div_di[7:0]; if (reg_div_we[1]) cfg_divider[15:8] <= reg_div_di[15:8]; if (reg_div_we[2]) cfg_divider[23:16] <= reg_div_di[23:16]; if (reg_div_we[3]) cfg_divider[31:24] <= reg_div_di[31:24]; end end always @(posedge clk) begin if (!resetn) begin recv_state <= 0; recv_divcnt <= 0; recv_pattern <= 0; recv_buf_data <= 0; recv_buf_valid <= 0; end else begin recv_divcnt <= recv_divcnt + 1; if (reg_dat_re) recv_buf_valid <= 0; case (recv_state) 0: begin if (!ser_rx) recv_state <= 1; recv_divcnt <= 0; end 1: begin if (2 * recv_divcnt > cfg_divider) begin recv_state <= 2; recv_divcnt <= 0; end end 10: begin if (recv_divcnt > cfg_divider) begin recv_buf_data <= recv_pattern; recv_buf_valid <= 1; recv_state <= 0; end end default: begin if (recv_divcnt > cfg_divider) begin recv_pattern <= {ser_rx, recv_pattern[7:1]}; recv_state <= recv_state + 1; recv_divcnt <= 0; end end endcase end end assign ser_tx = send_pattern[0]; always @(posedge clk) begin if (reg_div_we) send_dummy <= 1; send_divcnt <= send_divcnt + 1; if (!resetn) begin send_pattern <= ~0; send_bitcnt <= 0; send_divcnt <= 0; send_dummy <= 1; end else begin if (send_dummy && !send_bitcnt) begin send_pattern <= ~0; send_bitcnt <= 15; send_divcnt <= 0; send_dummy <= 0; end else if (reg_dat_we && !send_bitcnt) begin send_pattern <= {1'b1, reg_dat_di[7:0], 1'b0}; send_bitcnt <= 10; send_divcnt <= 0; end else if (send_divcnt > cfg_divider && send_bitcnt) begin send_pattern <= {1'b1, send_pattern[9:1]}; send_bitcnt <= send_bitcnt - 1; send_divcnt <= 0; end end end endmodule
#include <bits/stdc++.h> using namespace std; long long INF = (1e19); int n, m; int a[105]; bool cmp(int a, int b) { return a > b; } bool check(int d) { int i = 1, k = 0, ans = 0; while (a[i] - k > 0 && i <= n) { ans += (a[i] - k); if (i % d == 0) { k++; } if (ans >= m) { return true; } i++; } return false; } int main() { scanf( %d%d , &n, &m); int ans = 0; for (int i = 1; i <= n; i++) { scanf( %d , &a[i]); ans += a[i]; } if (ans < m) { printf( -1 ); } else { sort(a + 1, a + 1 + n, cmp); int l = 1, r = n, p; while (l <= r) { int mid = (l + r) / 2; if (check(mid)) { r = mid - 1; p = mid; } else { l = mid + 1; } } printf( %d n , p); } return 0; }
#include <cstdlib> #include <cstdarg> #include <cassert> #include <cctype> // tolower #include <ctime> #include <cmath> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <stdexcept> #include <map> #include <tuple> #include <unordered_map> #include <set> #include <list> #include <stack> #include <queue> #include <vector> #include <string> #include <limits> #include <utility> #include <memory> #include <numeric> #include <iterator> #include <algorithm> #include <functional> /* * g++ -g -std=c++11 -DBUG -D_GLIBCXX_DEBUG -Wall -Wfatal-errors -o cforce{,.cpp} * * TODO: * C++ dataframe * stl11 -> c++11 standard template lib in c++98 * overload >> for map and set, using (insert) iterator * chmod:: consider an algorithm stable to int64 overflow * shortest path algorithm * shortest path in a tree * maximum network flow * partial idx/iter sort * a prime number generator which traverses prime numbers w/ ++ * a divisor generator which traverses divisors efficiently * Apply1st ?! * Apply2nd and bind2nd ?! * count_if ( a.begin(), a.end(), a.second < x ) * Arbitrary-precision arithmetic / Big Integer / Fraction - rational num * tuple class --> cplusplus.com/reference/tuple * get<1>, get<2>, bind2nd ( foo ( get<2> pair ), val ) * isin( const T & val, first, last ) * fuinction composition in c++ * blogea.bureau14.fr/index.php/2012/11/function-composition-in-c11/ * cpp-next.com/archive/2010/11/expressive-c-fun-with-function-composition/ * TimeWrapper -- accumulate time of a function call * stackoverflow.com/questions/879408 * hash map -- possible hash value & obj % some_big_prime [ b272 ] * lower level can be a simple map to resolve hash collisions * add explicit everywhere necessary * bloom filters * heap -> how to update values in place / increase-key or decrease-key ... IterHeap ?! * median maintaince --> max_heap / min_heap * prim s min spaning tree alg. O ( m log n ) using heap contianing V - X vertices * kruskal algorithm minimum cost spanning tree with union find data structure * unique_ptr * hufman codes * simple arithmatic tests * longest common subsequence using seq. alignment type algorithm * longest common substring ( consequative subsequeance ) * Graham scan; en.wikipedia.org/wiki/Graham_scan * problem/120/F -- how to extend in order to calculate all-pair distances in a tree * compile time prime number calculator using templates * swith to type_cast < T1, T2 > for val2str & str2val * overload plus<> for two vectors?! * overloading operator << for tuple: * stackoverflow.com/questions/9247723 * bitmask class with iterator protocol * ??? segment tree +++ interval tree * ??? an lru cache: a heap which maintains last access, an a map which maintains key:value * ??? in lazy-union how to query size of a connected component( 437/D ) */ /* * @recepies * ---------------------------------------------- * odd / even * transform ( x.begin(), x.end(), x.begin(), bind2nd( modulus<int>(), 2 )); * count_if ( x.begin(), x.end(), bind2nd( modulus < int > (), 2)); * Apply2nd * max_element ( m.begin(), m.end(), Apply2nd < string, int , less < int > > ) * sort ( a.begin(), a.end(), Apply2nd < char, int , greater< int > > ) * count_if ( m.begin(), m.end(), Apply2nd < string, int, modulus < int > > ) * accumulate ( m.begin(), m.end(), 0.0, Apply2nd < int, double, plus < double > > ) * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ) * abs_diff * adjacent_difference ( a.begin(), a.end(), adj_diff.begin( ), abs_diff < int > ( ) ) * accumulate ( a.begin(), a.end(), 0, abs_diff < int > ( ) ) * erase * a.erase ( remove_if ( a.begin( ), a.end( ), bind2nd ( less < int >( ), 0 ) ), a.end( ) ) * a.erase ( remove ( a.begin( ), a.end( ), b.begin( ), b.end( ) ), a.end ( ) ) * binding * bind2nd ( mem_fun_ref (& ClassName::m_func ), arg ) // binds the argument of the object * iterator generators * generate_n ( back_inserter ( a ), n, rand ); // calls push_back * generate_n ( inserter( a, a.begin( ) + 5 ), 10, RandInt( 0 , 100 ) ) // calls insert * copy ( foo.begin( ), foo.end( ), insert_iterator < list < double > > ( bar, bar.begin( ) + 5 )) * copy ( a.begin( ), a.end( ), ostream_iterator < double > ( cout, , )) * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ) * transform (numbers.begin(), numbers.end(), lengths.begin(), mem_fun_ref(&string::length)); */ /* * @good read * ---------------------------------------------- * [ partial ] template specialization * cprogramming.com/tutorial/template_specialization.html * function composition * cpp-next.com/archive/2010/11/expressive-c-fun-with-function-composition */ /* * @prob set * ---------------------------------------------- * purification --> c330 */ /* * @limits * ---------------------------------------------- * int 31 2.14e+09 * long int 31 2.14e+09 * unsigned 32 4.29e+09 * long unsigned 32 4.29e+09 * size_t 32 4.29e+09 * long long int 63 9.22e+18 * long long unsigned 64 1.84e+19 */ /* * issues * ---------------------------------------------- * stackoverflow.com/questions/10281809 * mem_fun -> func_obj ( pointer to instance, origanal argument ) * bind1st ( mem_fun ( & ClassName::m_func ), this ) // binds obj of the class * bind1st takes const T & as the first argument */ /* * typedef / define * ---------------------------------------------- */ typedef long long int int64; typedef unsigned long long int uint64; #ifndef M_PI #define M_PI 3.14159265358979323846L #endif #define DOUBLE_INF numeric_limits< double >::infinity() #define DOUBLE_NAN numeric_limits< double >::quiet_NaN() #define __STR__(a) #a #define STR(a) __STR__(a) #define ASSERT(expr, msg) if (!( expr )) throw runtime_error(__FILE__ : STR(__LINE__) - msg); #define DECLARE( X ) typedef shared_ptr < X > X ## _shared_ptr; typedef const shared_ptr < X > X ## _const_shared_ptr; #ifdef BUG #define DEBUG(var) { cout << #var << : << (var) << endl; } #define COND_DEBUG(expr, var) if (expr) { cout << #var << : << (var) << endl; } #define EXPECT(expr) if ( ! (expr) ) cerr << Assertion << #expr failed at << __FILE__ << : << __LINE__ << endl; #else #define DEBUG(var) #define COND_DEBUG(expr, var) #define EXPECT(expr) #endif #define DBG(v) copy( v.begin(), v.end(), ostream_iterator < typeof( *v.begin() )> ( cout, ) ) #if __cplusplus < 201100 #define move( var ) var #endif /* * http://rootdirectory.de/wiki/SSTR() * usage: * SSTR( x^2: << x*x ) */ #define SSTR( val ) dynamic_cast< ostringstream & >( ostringstream() << dec << val ).str() using namespace std; /* https://www.quora.com/C++-programming-language/What-are-some-cool-C++-tricks */ // template <typename T, size_t N> // char (&ArraySizeHelper(T (&array)[N]))[N]; // #define arraysize(array) (sizeof(ArraySizeHelper(array))) /* * forward decleration * ---------------------------------------------- */ class ScopeTimer; /* * functional utils * ---------------------------------------------- */ template < typename T > struct abs_diff : binary_function < T, T, T > { typedef T value_type; inline value_type operator( ) ( const value_type & x, const value_type & y ) const { return abs( x - y ); } }; // template < class InputIterator, class T > // class isin : public binary_function < InputIterator, InputIterator, bool > // { // public: // typedef T value_type; // // isin ( const InputIterator & first, const InputIterator & last ): // m_first ( first ), m_last ( last ) { } // // bool operator ( ) ( const value_type & val ) const // { // return find ( m_first, m_last, val ) != m_last; // } // private: // const InputIterator m_first, m_last; // } template < typename value_type, typename cont_type > class isin : public unary_function < value_type, bool > { public: isin( const cont_type & vals ): m_vals ( vals ) { }; bool operator ( ) ( const value_type & x ) const { return find ( m_vals.begin( ), m_vals.end( ), x ) != m_vals.end( ); } private: const cont_type m_vals; }; /* * max_element, min_element, count_if ... on the 2nd element * eg: max_element ( m.begin(), m.end(), Apply2nd < string, int , less < int > > ) */ template < class T1, class T2, class BinaryOperation > class Apply2nd : binary_function < typename std::pair < T1, T2 >, typename std::pair < T1, T2 >, typename BinaryOperation::result_type > { public: typedef T1 first_type; typedef T2 second_type; typedef typename BinaryOperation::result_type result_type; typedef typename std::pair < first_type, second_type > value_type; inline result_type operator( ) ( const value_type & x, const value_type & y ) const { return binary_op ( x.second , y.second ); } private: BinaryOperation binary_op; }; /* * algo utils * ---------------------------------------------- */ /** * count the number of inversions in a permutation; i.e. how many * times two adjacent elements need to be swaped to sort the list; * 3 5 2 4 1 --> 7 */ template < class InputIterator > typename iterator_traits<InputIterator>::difference_type count_inv ( InputIterator first, InputIterator last ) { typedef typename iterator_traits<InputIterator>::difference_type difference_type; typedef typename iterator_traits<InputIterator>::value_type value_type; list < value_type > l; /* list of sorted values */ difference_type cnt = 0; for ( difference_type n = 0; first != last; ++first, ++n ) { /* count how many elements larger than *first appear before *first */ typename list < value_type >::iterator iter = l.begin( ); cnt += n; for ( ; iter != l.end( ) && * iter <= * first; ++ iter, -- cnt ) ; l.insert( iter, * first ); } return cnt; } template < class ForwardIterator, class T > inline void fill_inc_seq ( ForwardIterator first, ForwardIterator last, T val ) { for ( ; first != last; ++first, ++val ) * first = val; } template <class ForwardIterator, class InputIterator > ForwardIterator remove ( ForwardIterator first, ForwardIterator last, InputIterator begin, InputIterator end ) { ForwardIterator result = first; for ( ; first != last; ++ first ) if ( find ( begin, end, *first ) == end ) { *result = *first; ++result; } return result; } /* stackoverflow.com/questions/1577475 */ template < class RAIter, class Compare > class ArgSortComp { public: ArgSortComp ( const RAIter & first, Compare comp ): m_first ( first ), m_comp( comp ) { } inline bool operator() ( const size_t & i, const size_t & j ) const { return m_comp ( m_first[ i ] , m_first[ j ] ); } private: const RAIter & m_first; const Compare m_comp; }; /*! * usage: * vector < size_t > idx; * argsort ( a.begin( ), a.end( ), idx, less < Type > ( ) ); */ template < class RAIter, class Compare=less< typename RAIter::value_type > > void argsort( const RAIter & first, const RAIter & last, vector < size_t > & idx, Compare comp = Compare()) // less< typename RAIter::value_type >() ) { const size_t n = last - first; idx.resize ( n ); for ( size_t j = 0; j < n; ++ j ) idx[ j ] = j ; stable_sort( idx.begin(), idx.end(), ArgSortComp< RAIter, Compare >( first, comp )); } template < class RAIter, class Compare > class IterSortComp { public: IterSortComp ( Compare comp ): m_comp ( comp ) { } inline bool operator( ) ( const RAIter & i, const RAIter & j ) const { return m_comp ( * i, * j ); } private: const Compare m_comp; }; /*! * usage: * vector < list < Type >::const_iterator > idx; * itersort ( a.begin( ), a.end( ), idx, less < Type > ( ) ); */ template <class INIter, class RAIter, class Compare> void itersort ( INIter first, INIter last, vector < RAIter > & idx, Compare comp ) { /* alternatively: stackoverflow.com/questions/4307271 */ idx.resize ( distance ( first, last ) ); for ( typename vector < RAIter >::iterator j = idx.begin( ); first != last; ++ j, ++ first ) * j = first; sort ( idx.begin( ), idx.end( ), IterSortComp< RAIter, Compare > (comp ) ); } /* * string utils * ---------------------------------------------- */ inline void erase ( string & str, const char & ch ) { binder2nd < equal_to < char > > isch ( equal_to< char >(), ch ); string::iterator iter = remove_if ( str.begin(), str.end(), isch ); str.erase ( iter, str.end() ); } inline void erase ( string & str, const string & chrs ) { isin < char, string > isin_chrs ( chrs ); string::iterator iter = remove_if ( str.begin(), str.end(), isin_chrs ); str.erase ( iter, str.end() ); } template < typename value_type> inline string val2str ( const value_type & x ) { ostringstream sout ( ios_base::out ); sout << x; return sout.str(); } template < typename value_type> inline value_type str2val ( const string & str ) { istringstream iss ( str, ios_base::in ); value_type val; iss >> val; return val; } vector< string > tokenize( const string & str, const char & sep ) { /*! * outputs empty tokens and assumes str does not start with sep * corner cases: * empty string, one char string, * string starting/ending with sep, all sep, end with two sep */ vector < string > res; string::const_iterator follow = str.begin(), lead = str.begin(); while ( true ) { while ( lead != str.end() && * lead != sep ) ++ lead; res.push_back ( string( follow, lead ) ); if ( lead != str.end () ) follow = 1 + lead ++ ; else break; } return res; } /*! * chunk a string into strings of size [ at most ] k */ void chunk ( const string::const_iterator first, const string::const_iterator last, const size_t k, const bool right_to_left, list < string > & str_list ) { str_list.clear( ); if ( right_to_left ) /* chunk from the end of the string */ for ( string::const_iterator i, j = last; j != first; j = i ) { i = first + k < j ? j - k : first; str_list.push_back ( string ( i, j ) ); } else /* chunk from the begining of the string */ for ( string::const_iterator i = first, j; i != last; i = j ) { j = i + k < last ? i + k : last; str_list.push_back ( string ( i, j ) ); } } /*! * next lexicographically smallest string * within char set a..z */ string & operator++( string & s ) { /* find the first char from right less than z */ string::reverse_iterator j = find_if( s.rbegin( ), s.rend( ), bind2nd( less < char > ( ), z )); if ( j != s.rend( )) { ++ *j; fill( s.rbegin( ), j, a ); } else s.assign( s.length( ) + 1, a ); return s; } /*! if a starts with b */ inline bool starts_with( const string & a, const string & b ) { return !( a.size() < b.size() || mismatch( begin(b), end(b), begin(a) ).first != end(b) ); } /*! prefix tree */ auto get_prefix_tree( const vector< string > & word ) -> vector< map< char, size_t > > { typedef map< char, size_t > node; /* empty string as the first element */ vector< node > tree(1); for( const auto & w: word ) { /* start with empty string as the root node */ size_t root = 0; for( const auto & a : w ) { auto & ref = tree[ root ][ a ]; if ( ref == 0 ) /* new prefix, add to the end of tree */ { ref = tree.size(); tree.push_back( node() ); } root = ref; } } return tree; } /*! * getline ( cin, str ) * requires ctrl-D * cin >> str; does not pass after space char */ /* * number utils * ---------------------------------------------- */ class BigInteger { #if ULONG_MAX <= 1 << 32 typedef long long unsigned val_type; #else typedef long unsigned val_type; #endif const static int WSIZE = 32; const static val_type BASE = 1LL << WSIZE; public: private: list < val_type > val; /* val[ 0 ] is most significant */ bool pos; /* true if sign is positive */ }; /** * greatest common divisor - Euclid s alg. */ template < typename value_type > inline value_type gcd ( value_type a, value_type b ) { return ! b ? a : gcd( b, a % b ); } /** * prime factorization */ template < class T > void prime_factors( T n, map < T, size_t > & fac ) { for ( T k = 2; n > 1; ++ k ) if ( ! ( n % k ) ) { size_t & ref = fac[ k ]; while ( ! ( n % k ) ) { ++ ref; n /= k; } } } /* abs diff - safe for unsigned types */ template < class T > inline T absdiff( T a, T b ) { return a < b ? b - a : a - b; } namespace { template < class T > pair < T, T > __extgcd ( const T & x0, const T & y0, const T & x1, const T & y1, const T & r0, const T & r1 ) { const T q = r0 / r1; const T r2 = r0 % r1; if ( ! ( r1 % r2 ) ) return make_pair < T, T > ( x0 - q * x1, y0 - q * y1 ); const T x2 = x0 - q * x1; const T y2 = y0 - q * y1; return __extgcd ( x1, y1, x2, y2, r1, r2 ); } } /** * extended euclidean algorithm: a x + b y = gcd( a, b) * en.wikipedia.org/wiki/Extended_Euclidean_algorithm */ template < class value_type > inline pair < value_type, value_type > extgcd ( value_type a, value_type b ) { return a % b ? __extgcd < value_type > ( 1, 0, 0, 1, a, b ) : make_pair < value_type, value_type > ( 0, 1 ); } /** * modular multiplicative inverse * en.wikipedia.org/wiki/Modular_multiplicative_inverse */ template < class value_type > inline value_type modinv ( value_type a, value_type m ) { const pair < value_type, value_type > coef ( extgcd( a, m ) ); /* a needs to be coprime to the modulus, or the inverse won t exist */ if ( a * coef.first + m * coef.second != 1 ) throw runtime_error ( val2str( a ) + is not coprime to + val2str( m )); /* return a pos num between 1 & m-1 */ return ( m + coef.first % m ) % m; } inline bool isnan ( const double & a ) { return ! ( a == a ); } template < typename value_type > inline value_type mini ( int n, ... ) { va_list vl; va_start (vl, n); value_type res = va_arg ( vl, value_type ); for ( int i = 1; i < n; ++i ) { const value_type val = va_arg ( vl, value_type ); res = min ( res, val ); } va_end( vl ); return res; } template < typename value_type > inline value_type maxi ( int n, ... ) { va_list vl; va_start (vl, n); value_type res = va_arg ( vl, value_type ); for ( int i = 1; i < n; ++i ) { const value_type val = va_arg ( vl, value_type ); res = max ( res, val ); } va_end( vl ); return res; } // XXX look this up how is this implemented template < class T > inline int sign ( const T & x ) { if ( x == T() ) return 0; else if ( x < T() ) return -1; else return 1; } /* * change moduluos from n to m */ string chmod ( string num, const unsigned n, const unsigned m ) { const char * digit = 0123456789abcdefghijklmnopqrstuvwxyz ; transform ( num.begin(), num.end(), num.begin(), ::tolower ); isin < char, string > is_alpha_num ( digit ); assert ( find_if ( num.begin( ), num.end( ), not1 ( is_alpha_num ) ) == num.end( )); unsigned long long int val ( 0 ); if ( n == 10U ) { istringstream iss ( num, ios_base::in ); iss >> val; } else for ( string::const_iterator iter = num.begin( ); iter != num.end( ); ++ iter ) val = val * n + ( a <= *iter ? *iter - a + 10U : *iter - 0 ); if ( m == 10U ) { ostringstream sout ( ios_base::out ); sout << val; return sout.str ( ); } else { string res; for ( ; val ; val /= m ) res.push_back( digit [ val % m ] ); return res.length( ) ? string( res.rbegin( ), res.rend( )) : 0 ; } } template < class value_type > /* a^n mod m */ value_type powmod ( value_type a, const value_type & n, const value_type & m ) { if ( a == 1 || ! n ) return m != 1 ? 1 : 0; value_type res = 1; for ( value_type k = 1; k <= n; a = a * a % m, k = k << 1 ) if ( k & n ) res = ( res * a ) % m; return res; } template < class T > inline T atan(const T & x, const T & y) { return atan( y / x ) + ( x < 0 ) * M_PI; } /* * Fermat pseudoprime test * www.math.umbc.edu/~campbell/Computers/Python/numbthy.py * NOTE: since return type is bool, and powmod may break for ints, * the argument is always casted to long long */ inline bool is_pseudo_prime ( const long long & a ) { /* all the primes less than 1000 ( 168 primes )*/ const long long p [ ] = { 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73, 79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157, 163,167,173,179,181,191,193,197,199,211,223,227,229,233,239, 241,251,257,263,269,271,277,281,283,293,307,311,313,317,331, 337,347,349,353,359,367,373,379,383,389,397,401,409,419,421, 431,433,439,443,449,457,461,463,467,479,487,491,499,503,509, 521,523,541,547,557,563,569,571,577,587,593,599,601,607,613, 617,619,631,641,643,647,653,659,661,673,677,683,691,701,709, 719,727,733,739,743,751,757,761,769,773,787,797,809,811,821, 823,827,829,839,853,857,859,863,877,881,883,887,907,911,919, 929,937,941,947,953,967,971,977,983,991,997 }; const size_t n = sizeof( p ) / sizeof ( p[ 0 ] ); if ( a < p[ n - 1 ] + 1) return binary_search ( p, p + n , a ); if ( find_if ( p, p + n, not1 ( bind1st ( modulus< long long >( ), a ))) != p + n ) return false; const size_t k = a < 9006401LL ? 3 : a < 10403641LL ? 4 : a < 42702661LL ? 5 : a < 1112103541LL ? 6 : 7; for ( size_t j = 0; j < k; ++ j ) if ( powmod ( p[ j ], a - 1, a ) != 1 ) return false; return true; } /* * returns a sorted vector of all primes less than or equal to n * maximum adj diff of all primes less than 1e5 is 72 ( 114 for 1e6 ) */ template < typename value_type > vector < value_type > get_primes ( const value_type n ) { #ifdef BUG ScopeTimer scope_timer ( vector < value_type > get_primes ( const value_type n ) ); #endif // typedef typename vector < value_type >::iterator iterator; vector < value_type > primes; for ( value_type k = 2 ; k <= n; ++ k ) if ( is_pseudo_prime ( k ) ) { // FIXME this is very stupid // const value_type sqrt_k = 1 + static_cast < value_type > ( sqrt ( k + 1 ) ); // iterator iend = upper_bound ( primes.begin( ), primes.end( ), sqrt_k ); // if ( find_if ( primes.begin( ), iend, not1 ( bind1st ( modulus< value_type >( ), k ) ) ) != iend ) // continue; primes.push_back ( k ); } return primes; } template < class T > inline vector < pair < T, size_t > > get_prime_fact( T a ) { vector< pair < T, size_t > >fac; for ( T k = 2; a > 1; ++ k ) if ( ! ( a % k ) ) // no need to check if k is prime { size_t m = 0; for ( ; ! ( a % k ) ; ++m, a/= k ) ; fac.push_back ( pair < T, size_t > ( k, m ) ); } return fac; } template < class T > /* prime factorization */ vector < pair < T, size_t > > get_prime_fac( T a ) { vector < pair < T, size_t > > fac; size_t k = 0; while (!(a % 2)) { a /= 2; ++ k; } if ( k != 0 ) fac.push_back( make_pair(2, k)); k = 0; while (!(a % 3)) { a /= 3; ++ k; } if ( k != 0 ) fac.push_back( make_pair(3, k)); for ( T j = 5; j * j < a + 1 && a > 1 && j < a + 1; j += 4 ) { size_t k = 0; while (!(a % j)) { a /= j; ++ k; } if ( k != 0 ) fac.push_back( make_pair(j, k)); j += 2; k = 0; while (!(a % j)) { a /= j; ++ k; } if ( k != 0 ) fac.push_back( make_pair(j, k)); } if ( a > 1 ) fac.push_back( make_pair(a, 1)); return fac; } template < class T > /* generates all divisors from vector of prime factorization */ void gen_div( T a, vector < T > & divs, typename vector < pair < T, size_t > >::const_iterator iter, typename vector < pair < T, size_t > >::const_iterator last ) { if ( iter != last ) { auto next = iter + 1; const auto k = iter->second + 1; const auto prime = iter->first; for ( size_t j = 0; j < k; ++ j ) { gen_div(a, divs, next, last); a *= prime; } } else divs.push_back( a ); } template < class T > T n_choose_k ( T n, T k ) { if ( k > n ) return 0; const T lb = min ( k, n - k ) + 1; const T ub = n - lb + 1; T res = 1, j = 2; while ( n > ub && j < lb) { res *= n--; while ( j < lb and ! (res % j) ) res /= j++; } while ( n > ub ) res *= n--; return res; } /** * median calculator, using two heaps */ template < class InputIter > inline pair < typename InputIter::value_type, typename InputIter::value_type > median ( InputIter first, InputIter last ) { typedef typename InputIter::value_type value_type; typedef pair< value_type, value_type > result_type; /* * max_heap: * - the lower half of the elements * - the biggest of such elements is on the top */ vector < value_type > max_heap, min_heap; /* * comp argument to heap algorithm should provide * strict weak ordering ; in particular * not2 ( less < value_type > ) * does not have such a strict weak ordering; */ less < value_type > max_heap_comp; greater < value_type > min_heap_comp; if ( first == last ) /* corner case: empty vector */ throw runtime_error ( median of an empty vector is undefined! ); InputIter iter = first; max_heap.push_back ( * iter ); for ( ++iter ; iter != last; ++ iter ) if ( * iter < max_heap.front() ) { max_heap.push_back ( * iter ); push_heap ( max_heap.begin(), max_heap.end(), max_heap_comp ); if ( min_heap.size() + 1 < max_heap.size() ) { /* max_heap has got too large */ min_heap.push_back( max_heap.front() ); push_heap( min_heap.begin(), min_heap.end(), min_heap_comp ); pop_heap( max_heap.begin(), max_heap.end(), max_heap_comp ); max_heap.pop_back(); } } else { min_heap.push_back ( * iter ); push_heap ( min_heap.begin(), min_heap.end(), min_heap_comp ); if ( max_heap.size() + 1 < min_heap.size() ) { /* min_heap has got too large */ max_heap.push_back( min_heap.front() ); push_heap( max_heap.begin(), max_heap.end(), max_heap_comp ); pop_heap( min_heap.begin(), min_heap.end(), min_heap_comp ); min_heap.pop_back(); } } DEBUG( max_heap ); DEBUG( min_heap ); return min_heap.empty( ) /* corner case: ++first = last */ ? result_type ( *first, *first ) : result_type ( max_heap.size() < min_heap.size() ? min_heap.front() : max_heap.front(), min_heap.size() < max_heap.size() ? max_heap.front() : min_heap.front() ); } /* * geometry util * ---------------------------------------------- */ struct xyPoint { double x, y; xyPoint( const double & a = .0, const double & b = .0 ): x ( a ), y( b ) { }; }; struct xyCircle { xyPoint center; double radius; }; ostream & operator<< ( ostream & out, const xyPoint & p ) { out << ( << p.x << , << p.y << ) ; return out; } istream & operator>> ( istream & ist, xyPoint & p ) { ist >> p.x >> p.y; return ist; } ostream & operator<< ( ostream & out, const xyCircle & o ) { out << {( << o.center.x << , << o.center.y << ) << o.radius << } ; return out; } istream & operator>> ( istream & ist, xyCircle & o ) { ist >> o.center.x >> o.center.y >> o.radius; return ist; } inline double cartesian_dist ( const xyPoint & a, const xyPoint & b ) { const double d = a.x - b.x; const double e = a.y - b.y; return sqrt ( d * d + e * e ); } class xyLine { public: xyLine ( const xyPoint & , const xyPoint & ); xyLine ( const double slope, const double intercept ); /* * signed orthogonal distance; the sign is useful * to compare which side of the line the point is */ inline double orth_dist ( const xyPoint & ) const; private: double m_slope; double m_intercept; double m_normfac; /* normalization factor for orth_dist calc */ bool m_vertical; /* if the line is verticcal */ double m_xcross; /* x axis cross point for vertical line */ }; xyLine::xyLine ( const xyPoint & a, const xyPoint & b ) { if ( a.x == b.x ) /* vertical line */ { m_vertical = true; m_xcross = a.x; m_intercept = DOUBLE_NAN; m_slope = DOUBLE_INF; m_normfac = DOUBLE_NAN; } else { m_vertical = false; m_xcross = DOUBLE_NAN; m_slope = ( b.y - a.y ) / ( b.x - a.x ); m_intercept = a.y - m_slope * a.x; m_normfac = sqrt ( m_slope * m_slope + 1.0 ); } } xyLine::xyLine ( const double slope, const double intercept ): m_slope ( slope ), m_intercept ( intercept ) { m_vertical = false; m_xcross = DOUBLE_NAN; m_normfac = sqrt ( m_slope * m_slope + 1.0 ); } double xyLine::orth_dist ( const xyPoint & o ) const /* signed orthogonal distance */ { if ( m_vertical ) return o.x - m_xcross; else return ( m_slope * o.x - o.y + m_intercept ) / m_normfac; } inline double triangle_area ( const xyPoint & a, const xyPoint & b, const xyPoint & c ) { const xyLine l ( a, b ); const double h = abs ( l.orth_dist ( c ) ); const double e = cartesian_dist ( a, b ); return h * e; } /* * operator<< overrides * ---------------------------------------------- */ namespace { /* helper function to output containers */ template < typename T > ostream & __output ( ostream & out, const T & a ) { typedef typename T::const_iterator const_iterator; out << { ; // does not work for pair value type // copy ( a.begin( ), a.end( ), ostream_iterator < typename T::value_type > ( cout, , )); for ( const_iterator iter = a.begin(); iter != a.end(); ++ iter ) out << ( iter != a.begin( ) ? , : ) << *iter ; return out << } ; } } template < typename key_type, typename value_type > ostream & operator<< ( ostream & out, const pair < key_type, value_type > & p) { out << ( << p.first << , << p.second << ) ; return out; } template < typename T0, typename T1, typename T2 > ostream & operator<< ( ostream & out, const tuple < T0, T1, T2 > & t ) { out << ( << get<0>(t) << , << get<1>(t) << , << get<2>(t) << ) ; return out; } template < typename T0, typename T1 > ostream & operator<< ( ostream & out, const tuple < T0, T1 > & t ) { out << ( << get<0>(t) << , << get<1>(t) << ) ; return out; } template < typename key_type, typename value_type, typename comp > ostream & operator<< ( ostream & out, const map < key_type, value_type, comp > & m ) { return __output ( out, m ); } template < typename value_type, typename comp > ostream & operator<< ( ostream & out, const set < value_type, comp > & s ) { return __output ( out, s ); } template < typename value_type > ostream & operator<< ( ostream & out, const vector < value_type > & a ) { return __output ( out, a ); } template < typename value_type > ostream & operator<< ( ostream & out, const list < value_type > & a ) { return __output ( out, a ); } template < typename value_type > ostream & operator<< ( ostream & out, const vector < vector < value_type > > & a ) { typedef typename vector < vector < value_type > >::const_iterator const_iterator; for ( const_iterator iter = a.begin( ); iter != a.end( ); ++ iter ) out << n << *iter ; return out; } /* * operator>> overrides * ---------------------------------------------- */ template < typename key_type, typename value_type > istream & operator>> ( istream & in, pair < key_type, value_type > & p) { in >> p.first >> p.second; return in; } template < typename T0, typename T1, typename T2 > istream & operator>> ( istream & fin, tuple < T0, T1, T2 > & t ) { fin >> get<0>(t) >> get<1>(t) >> get<2>(t); return fin; } template < typename value_type > istream & operator>> ( istream & in, vector < value_type > & a ) { typedef typename vector < value_type >::iterator iterator; if ( ! a.size( ) ) { size_t n; in >> n; a.resize( n ); } for ( iterator iter = a.begin(); iter != a.end(); ++ iter ) in >> * iter; return in; } /* * readin quick utilities * ---------------------------------------------- */ // template < typename value_type > // inline void readin ( vector < value_type > & a, size_t n = 0, istream & in = cin ) // { // // if ( ! n ) cin >> n; // if ( ! n ) in >> n ; // a.resize ( n ); // // cin >> a; // in >> a; // } // XXX consider removing // template < typename key_type, typename value_type > // inline void readin (vector < pair < key_type , value_type > > & a, size_t n = 0 ) // { // if ( !n ) cin >> n; // a.resize( n ); // cin >> a; // } /* * pair utility * ---------------------------------------------- */ /* * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ); * stackoverflow.com/questions/18640152 */ template < typename T1, typename T2 > inline pair < T1, T2 > operator+ ( const pair < T1, T2 > & a, const pair < T1, T2 > & b ) { return make_pair < T1, T2 > ( a.first + b.first, a.second + b.second ); } template < typename T1, typename T2 > inline pair < T1, T2 > operator- ( const pair < T1, T2 > & a, const pair < T1, T2 > & b ) { return make_pair < T1, T2 > ( a.first - b.first, a.second - b.second ); } // template < class T1, class T2, class BinaryOperation > // class Apply2nd : binary_function < typename pair < T1, T2 >, // typename pair < T1, T2 >, // typename BinaryOperation::result_type > namespace { /*! * helper template to do the work */ template < size_t J, class T1, class T2 > struct Get; template < class T1, class T2 > struct Get < 0, T1, T2 > { typedef typename pair < T1, T2 >::first_type result_type; static result_type & elm ( pair < T1, T2 > & pr ) { return pr.first; } static const result_type & elm ( const pair < T1, T2 > & pr ) { return pr.first; } }; template < class T1, class T2 > struct Get < 1, T1, T2 > { typedef typename pair < T1, T2 >::second_type result_type; static result_type & elm ( pair < T1, T2 > & pr ) { return pr.second; } static const result_type & elm ( const pair < T1, T2 > & pr ) { return pr.second; } }; } template < size_t J, class T1, class T2 > typename Get< J, T1, T2 >::result_type & get ( pair< T1, T2 > & pr ) { return Get < J, T1, T2 >::elm( pr ); } template < size_t J, class T1, class T2 > const typename Get< J, T1, T2 >::result_type & get ( const pair< T1, T2 > & pr ) { return Get < J, T1, T2 >::elm( pr ); } /* * graph utils * ---------------------------------------------- */ /* maximum in sub-tree distance */ void get_indist( const size_t root, const vector < vector < size_t > > & tree, vector < tuple< size_t, size_t > > & indist ) { const auto NIL = numeric_limits< size_t >::max(); size_t a = 0, b = NIL; for ( const auto u: tree[ root ] ) { get_indist( u, tree, indist ); if ( a < 1 + get< 0 >( indist[ u ] ) ) { b = a; a = 1 + get< 0 >( indist[ u ] ); } else b = b != NIL ? max( b, 1 + get< 0 >( indist[ u ] )) : 1 + get< 0 >( indist[ u ] ); } indist[ root ] = make_tuple(a, b); } /* maximum out of subtree distance */ void get_outdist( const size_t root, const vector< vector< size_t > > & tree, const vector< tuple< size_t, size_t > > & indist, vector < size_t > & outdist ) { const auto NIL = numeric_limits< size_t >::max(); for( const auto u: tree[ root ] ) { if ( 1 + get< 0 >( indist[ u ] ) == get< 0 >( indist[ root ] ) ) outdist[ u ] = get< 1 >( indist[ root ] ) != NIL ? 1 + max( get< 1 >( indist[ root ] ), outdist[ root ] ) : 1 + outdist[ root ]; else outdist[ u ] = 1 + max( get< 0 >( indist[ root ] ), outdist[ root ] ); get_outdist( u, tree, indist, outdist ); } } /* * Dijkstra :: single-source shortest path problem for * a graph with non-negative edge path costs, producing * a shortest path tree * en.wikipedia.org/wiki/Dijkstra s_algorithm */ template < typename DistType > void Dijekstra ( const size_t & source, const vector < list < size_t > > & adj, // adjacency list const vector < vector < DistType > > & edge_len, // pair-wise distance for adjacent nodes vector < DistType > & dist, // distance from the source vector < size_t > prev ) // previous node in the shortest path tree { // TODO } // TODO http://en.wikipedia.org/wiki/Shortest_path_problem // TODO Graph class, Weighted graph, ... /* * maximum cardinality matching in a bipartite graph * G = G1 ∪ G2 ∪ {NIL} * where G1 and G2 are partition of graph and NIL is a special null vertex * https://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm */ class HopcroftKarp { public: HopcroftKarp ( const vector < list < size_t > > & adj, const vector < bool > & tag ); size_t get_npair ( ) { return npair; }; map < size_t, size_t > get_map ( ); private: bool mf_breadth_first_search ( ); // breadth first search from unpaired nodes in G1 bool mf_depth_first_search ( const size_t v ); // dfs w/ toggeling augmenting paths const vector < list < size_t > > & m_adj; // adjacency list for each node const vector < bool > & m_tag; // binary tag distinguishing partitions size_t npair; const size_t NIL; // special null vertex const size_t INF; // practically infinity distance vector < size_t > m_g1; // set of nodes with tag = true vector < size_t > m_dist; // dist from unpaired vertices in G1 vector < size_t > m_pair; }; map < size_t, size_t > HopcroftKarp::get_map ( ) { map < size_t, size_t > m; for ( size_t j = 0; j < m_pair.size( ); ++ j ) if ( m_pair[ j ] != NIL && m_tag[ j ]) m[ j ] = m_pair[ j ]; return m; } HopcroftKarp::HopcroftKarp ( const vector < list < size_t > > & adj, const vector < bool > & tag ): m_adj ( adj ), m_tag ( tag ), npair ( 0 ), NIL ( adj.size( )), INF ( adj.size( ) + 1 ), m_dist ( vector < size_t > ( adj.size( ) + 1, INF)), m_pair ( vector < size_t > ( adj.size( ), NIL )) // initially everything is paired with nil { assert ( m_adj.size() == m_tag.size() ); for ( size_t j = 0; j < tag.size( ); ++ j ) if ( tag[ j ] ) m_g1.push_back ( j ); while ( mf_breadth_first_search ( ) ) for ( vector < size_t >::const_iterator v = m_g1.begin( ); v != m_g1.end( ); ++ v ) if ( m_pair[ *v ] == NIL && mf_depth_first_search ( *v ) ) ++ npair; } bool HopcroftKarp::mf_breadth_first_search( ) { /* only nodes from g1 are queued */ queue < size_t > bfs_queue; /* initialize queue with all unpaired nodes from g1 */ for ( vector < size_t >::const_iterator v = m_g1.begin( ); v != m_g1.end( ); ++v ) if ( m_pair[ *v ] == NIL ) { m_dist[ *v ] = 0; bfs_queue.push ( *v ); } else m_dist[ *v ] = INF; m_dist[ NIL ] = INF; /* find all the shortest augmenting paths to node nil */ while ( ! bfs_queue.empty() ) { const size_t v = bfs_queue.front( ); bfs_queue.pop ( ); if ( m_dist[ v ] < m_dist[ NIL ] ) for ( list < size_t >::const_iterator u = m_adj[ v ].begin( ); u != m_adj[ v ].end( ); ++ u ) if ( m_dist[ m_pair[ * u ] ] == INF ) { m_dist[ m_pair[ * u ] ] = m_dist[ v ] + 1; bfs_queue.push ( m_pair[ * u ] ); } } return m_dist[ NIL ] != INF; } bool HopcroftKarp::mf_depth_first_search( const size_t v ) { if ( v == NIL ) return true; else { for ( list < size_t >::const_iterator u = m_adj[ v ].begin( ); u != m_adj[ v ].end( ); ++ u ) if ( m_dist[ m_pair[ *u ] ] == m_dist[ v ] + 1 && mf_depth_first_search( m_pair[ *u ] )) { /* * there is an augmenting path to nil from m_pair[ *u ] * and hence there is an augmenting path from v to u and * u to to nil; therefore v and u can be paired together */ m_pair [ *u ] = v; m_pair [ v ] = *u; return true; } m_dist[ v ] = INF; return false; } } /** * lazy all pairs shortest path in a tree with only one BFS * test case: book of evil * codeforces.com/problemset/problem/337/D */ class All_Pairs_Tree_Shortest_Path { public: All_Pairs_Tree_Shortest_Path( const vector< list < size_t > > & adj ): n( adj.size( ) ), depth( vector < size_t > ( n, All_Pairs_Tree_Shortest_Path::INF ) ), parent( vector < size_t > ( n ) ), dist( vector < vector < unsigned short > > ( n ) ) { /* perform bfs from root node 0 and assign depth to each node */ /* XXX probably would be worth to set the root as node with highest degree */ queue< size_t > bfs_queue; bfs_queue.push( 0 ); depth[ 0 ] = 0; parent[ 0 ] = 0; while ( ! bfs_queue.empty( ) ) { const size_t u = bfs_queue.front( ); bfs_queue.pop( ); for ( list< size_t >::const_iterator j = adj[ u ].begin( ); j != adj[ u ].end( ); ++ j ) if ( depth[ u ] + 1 < depth[ *j ] ) { depth[ *j ] = depth[ u ] + 1; parent[ *j ] = u; bfs_queue.push( *j ); } } /* adjust pair-wise distance to zero along the diagonal */ for ( size_t j = 1; j < n; ++ j ) dist[ j ].resize( j, All_Pairs_Tree_Shortest_Path::INF ); } /* interface object function as to lazily look-up distances */ size_t operator( )( const size_t u, const size_t v ) { if ( u == v ) return 0; else if ( u < v) return (*this)( v, u ); else if ( dist[ u ][ v ] == All_Pairs_Tree_Shortest_Path::INF ) { if ( depth[ u ] < depth[ v ] ) /* u is in a lower level than v */ dist[ u ][ v ] = 1 + (*this)( u, parent[ v ]); else if ( depth[ v ] < depth[ u ] ) /* v is in a lower level than u */ dist[ u ][ v ] = 1 + (*this)( parent[ u ], v ); else /* u and v are at the same depth */ dist[ u ][ v ] = 2 + (*this)( parent[ u ], parent[ v ] ); } return dist[ u ][ v ]; } /* TODO populate; a method which populates pair-wise distances * and returns the matrix */ private: /* * constant infinity value for initializing distances * even though this is private it will be assigned outside of the class */ static const unsigned short INF; const size_t n; /* numbert of nodes in the tree */ vector < size_t > depth; /* distance to root node 0 */ vector < size_t > parent; /* parent of each node with root node 0 */ vector < vector < unsigned short > > dist; /* pair-wise shortest path distance */ }; const unsigned short All_Pairs_Tree_Shortest_Path::INF = numeric_limits< unsigned short >::max( ); /* * data-structure utility * ---------------------------------------------- */ template < class T, class Comp = less< T > > class Heap /* less< T > --> max-heap */ { typedef T value_type; typedef typename vector < value_type >::size_type size_type; public: /* * stackoverflow.com/questions/10387751 * possible work-around: a memebr pointer to m_val * TODO static/friend heapify ( val, & heap ) XXX O( n ) ?! * TODO implement insert iterator */ Heap(): m_val( vector < value_type >() ), m_comp( Comp() ) {} Heap( const Comp & comp ): m_val( vector< value_type >() ), m_comp( comp ){ } template < class InputIter > Heap ( InputIter first, InputIter last ): m_val ( vector < value_type > ( ) ), m_comp( Comp( ) ) { for ( ; first != last ; ++ first ) m_val.push_back ( * first ); make_heap( m_val.begin( ), m_val.end( ), m_comp ); } /*! * to avoid destroying heap property, front( ) * should always return a const reference */ inline const value_type & front( ) const { return m_val.front( ); } inline bool empty( ) const { return m_val.empty( ); } inline size_type size( ) const { return m_val.size( ); } inline void push( const value_type & a ) { m_val.push_back( a ); push_heap( m_val.begin( ), m_val.end( ), m_comp ); } inline void pop( ) { pop_heap ( m_val.begin( ), m_val.end( ), m_comp ); m_val.pop_back( ); } // inline void swap( Heap< T, Comp> & other ) { m_val.swap( other.m_val ) }; // void sort( ) { sort_heap ( m_val.begin( ), m_val.end( ), m_comp ); } // template < class X, class Y > // friend ostream & operator<<( ostream & out, const Heap < X, Y> & heap ); private: vector < value_type > m_val; const Comp m_comp; }; /* * boost.org/doc/libs/1_54_0/libs/smart_ptr/shared_ptr.htm */ #if 1 < 0 template < class Type > class shared_ptr { typedef Type value_type; public: explicit shared_ptr ( value_type * p = NULL ) : ptr ( p ), count ( new size_t ( 1U ) ) { } shared_ptr ( const shared_ptr < value_type > & sp ): ptr ( sp.ptr ), count ( sp.count ) { ++ * count; } ~ shared_ptr ( ) { release( ); } bool operator== ( const shared_ptr < value_type > & sp ) { return ptr == sp.ptr; } bool operator!= ( const shared_ptr < value_type > & sp ) { return ptr != sp.ptr; } shared_ptr < value_type > & operator= ( const shared_ptr < value_type > & sp ) { if ( this != & sp && ptr != sp.ptr ) { release( ); ptr = sp.ptr; count = sp.count; ++ * count; } return * this; } value_type * operator-> ( ) { return ptr ; } value_type & operator* ( ) { return *ptr ; } const value_type * operator-> ( ) const { return ptr ; } const value_type & operator* ( ) const { return *ptr; } void swap ( shared_ptr < value_type > & sp ) { if ( this != &sp && ptr != sp.ptr ) { swap ( ptr, sp.ptr ); swap ( count, sp.count ); } } private: void release ( ) { /* stackoverflow.com/questions/615355 */ -- * count; if ( ! * count ) { delete count; delete ptr; count = NULL; ptr = NULL; } } value_type * ptr; size_t * count; }; #endif /*! * union find data structure with * - lazy unions * - union by rank * - path compression */ class UnionFind { public: UnionFind( const size_t n ): parent ( vector < size_t > ( n ) ), /* initialize each node as its own */ rank ( vector < size_t > ( n, 0 )) /* parent and set all the ranks to 0 */ { for ( size_t j = 0; j < n; ++ j ) parent[ j ] = j ; } inline size_t find( const size_t s ) { /* * perform path compresion and add shortcut * if parent[ s ] is not a root node */ const size_t p = parent[ s ]; return parent[ p ] == p ? p : parent[ s ] = find( p ) ; } inline void lazy_union ( size_t i, size_t j ) { /* unions should be done on root nodes */ i = find( i ); j = find( j ); if ( i != j ) { if ( rank [ i ] < rank[ j ] ) parent[ i ] = j; else { parent[ j ] = i; rank[ i ] += rank[ i ] == rank[ j ]; } } } private: vector < size_t > parent; vector < size_t > rank; }; // TODO XXX // template < class NumType > // unsigned num_hash_func ( const NumType & a ) // { // // XXX what will happen in case of overflow? // return static_cast < unsigned > ( a % 9973 ) % 9973 ; // } /* * XXX: HashMap: map< Key, T > data [ 9973 ] * data [ num_hash_func ( key ) ][ key ] */ /* * testing util * ---------------------------------------------- */ // TODO add a preprocessor which automatically includes the funciton name, or __line__ // and disables if not in debug mode /* prints the life length of the object when it goes out of scope */ class ScopeTimer { public: ScopeTimer ( const string & msg = ): tic ( clock ( )), m_msg( msg ) { }; ~ ScopeTimer ( ) { const clock_t toc = clock(); const uint64 dt = 1000L * ( toc - tic ) / CLOCKS_PER_SEC; const uint64 mil = dt % 1000L; const uint64 sec = ( dt / 1000L ) % 60L; const uint64 min = ( dt / 60000L ) % 60L; const uint64 hrs = ( dt / 3600000L ); cout << n << m_msg << n telapsed time: ; if ( hrs ) cout << hrs << hrs, ; if ( min ) cout << min << min, ; if ( sec ) cout << sec << sec, ; cout << mil << mil-sec n ; } private: typedef unsigned long long int uint64; const clock_t tic; const string m_msg; }; class RandInt { public: RandInt ( int a = 0, int b = 100 ): m ( a ), f ( static_cast < double > ( b - a ) / RAND_MAX ) { } inline int operator() ( ) { return m + ceil ( f * rand( ) ); } private: const int m; const double f; }; class RandDouble { public: RandDouble ( double a = 0.0, double b = 1.0 ): m ( a ), f ( ( b - a ) / RAND_MAX ) { } inline double operator() ( ) { return m + f * rand( ); } private: const double m, f; }; class Noisy { public: Noisy ( string str ): msg ( str ) { cout << Noisy ( << msg << ) t@ << this << endl; } ~Noisy ( ) { cout << ~Noisy ( << msg << ) t@ << this << endl; } void beep ( ) { cout << beep ( << msg << ) t@ << this << endl; } void beep ( ) const { cout << const beep ( << msg << ) t@ << this << endl; } private: const string msg; }; DECLARE ( Noisy ); /* * ---------------------------------------------- * ---------------------------------------------- */ /* * -- @@@ ------------------------------------------------- */ inline int minchar( const size_t j, const vector< int > & a ) { const auto n = a.size(); int k = 0; while( ( j + 1 < n && a[ j + 1 ] == k ) || ( j + 2 < n && a[ j + 2 ] == k )) ++ k; return k; } void probA() { size_t n; int k; cin >> n >> k; string str; cin >> str; vector< int > a( n ); transform(begin(str), end(str), a.rbegin(), bind(minus<char>(), placeholders::_1, a )); // first letter that can increase size_t j = 0; // find_if(begin(a), end(a), bind(less<int>(), placeholders::_1, k)) - begin(a); bool flag = false; while( j < n && ! flag ) { ++ a[ j ]; while( ( j + 1 < n && a[ j ] == a[ j + 1 ]) || ( j + 2 < n && a[ j ] == a[ j + 2 ] )) ++ a[ j ]; if( k < 1 + a[ j ] ) { ++ j; continue; } bool fail = false; for( size_t i = j; 0 < i && !fail; -- i ) { a[ i - 1 ] = minchar(i - 1, a); fail = k < 1 + a[ i - 1 ]; } flag = ! fail; } if( !flag ) cout << NO ; else { for( auto iter = a.rbegin(); iter != a.rend(); ++ iter ) cout << (char)( a + *iter); } } int main ( const int argc, char * argv [ ]) { probA(); // cout << setprecision( 10 ) return EXIT_SUCCESS; } /** * mislav.uniqpath.com/2011/12/vim-revisited/ * set encoding=utf-8 * %s/ (. {60,70 } ) / 1 r/gc * %s/ / /gc * %s/10 ([0-9] {1,2 } )/10^ 1/gc */
`timescale 1ns / 1ps module RX #( parameter stateA = 'b00001, parameter stateB = 'b00010, parameter stateC = 'b00100, parameter stateD = 'b01000, parameter stateE = 'b10000) (input clk, input baud_rate, input rx, output reg [7:0] d_out, output reg rx_done); integer state = stateA; integer next_state = stateA; reg tick_enable = 0; integer count = 0; reg rst_count = 1; integer bits_count = 0; always@(posedge clk) begin state = next_state; end always@(posedge clk) begin case(state) //el estado A espera por el bit de start stateA: if(rx == 1) next_state = stateA; else next_state = stateB; //una vez recibido el bit de start se pasa al estado B, donde se //esperan 7 cuentas stateB: if(count == 7) next_state = stateC; else next_state = stateB; //cuando se cumplen las 7 cuentas se pasa al estado C, en donde //se resetea el counter y se pasa inmediatamente al proximo estado stateC: next_state = stateD; //en el estado B, se comienzan a recibir los datos //cuando se cumplen los 8 bits, se pasa al estado E stateD: if(bits_count == 8) next_state = stateE; else next_state = stateD; //en el estado E se espera por el bit de stop para volver al estado idle stateE: if(rx_done == 1) next_state = stateA; else next_state = stateE; endcase end always@(posedge clk) begin case(state) //en el estado A, se deshabilita el contador y rx_done se pone en 0 stateA: begin rst_count = 1; tick_enable = 0; rx_done = 0; end //en el estado B se habilita el contador, y se esperan 7 cuentas para //pasar al estado C stateB: begin tick_enable = 1; end //en el estado C se resetea el contador y se pasa inmediatamente //al estado D stateC: begin rst_count = 0; end //en el estado B, cada vez que la cuenta llega a 16, se toma un bit y se guarda en d_out //se incrementa la cuenta de bits leidos y se resetea el contador stateD: begin rst_count = 1; if(count == 16) begin d_out = d_out>>1; d_out[7] = rx; bits_count = bits_count + 1; rst_count = 0; end end stateE: begin if(count == 16 && rx == 1) begin rx_done = 1; bits_count = 0; rst_count = 0; end end endcase end //contador de ticks always@(posedge baud_rate or negedge rst_count) begin //reset cuenta if(rst_count == 0) count = 0; //contar si esta habilitado else begin if(tick_enable == 1) count = count+1; end end endmodule
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using vi = vector<int>; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, m, c; cin >> n >> m >> c; vector<int> v1, v2; for (int i = 0; i < m; i++) { int t; cin >> t; if (t <= c / 2) { int ind = upper_bound((v1).begin(), (v1).end(), t) - v1.begin(); if (ind == v1.size()) v1.emplace_back(); v1[ind] = t; cout << ind + 1 << endl; } else { int ind = upper_bound((v2).begin(), (v2).end(), -t) - v2.begin(); if (ind == v2.size()) v2.emplace_back(); v2[ind] = -t; cout << n - ind << endl; } if (v1.size() + v2.size() == n) return 0; } }
class foo(); int my_field; endclass // foo class temp; extern function test(); extern function test2(); function foo(); foo = 1; endfunction // foo extern function test3(); reg [31:0] b; endclass // temp class short extends temp; logic a; endclass `define vmm_channel(A) A+A module foo; reg a; reg [1:0] b; initial begin b = `vmm_channel(a); end // initial begin endmodule // foo class A; extern function int e1(); extern function int e2(int src,int dst); extern static function int f1(); extern static function int f2(int src,int dst); extern static function int f3(int src,int dst); extern static function chandle f10(int src); extern static function automatic int f11(int mcid); extern function automatic int f13(int mcid); static function int s1(); int i = 0; endfunction static function int s2(); int i = 0; endfunction function int f1(); int i = 0; endfunction function int f2(); int i = 0; endfunction endclass
/*============================================================================ This Verilog source file is part of the Berkeley HardFloat IEEE Floating-Point Arithmetic Package, Release 1, by John R. Hauser. Copyright 2019 The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =============================================================================*/ `include "HardFloat_consts.vi" `include "HardFloat_specialize.vi" /*---------------------------------------------------------------------------- *----------------------------------------------------------------------------*/ module test_addRecFN_sub#(parameter expWidth = 3, parameter sigWidth = 3); /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ parameter maxNumErrors = 20; /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ localparam formatWidth = expWidth + sigWidth; /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ reg [(`floatControlWidth - 1):0] control; reg [2:0] roundingMode; reg [(formatWidth - 1):0] a, b, expectOut; reg [4:0] expectExceptionFlags; /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ wire [formatWidth:0] recA, recB, recExpectOut; fNToRecFN#(expWidth, sigWidth) fNToRecFN_a(a, recA); fNToRecFN#(expWidth, sigWidth) fNToRecFN_b(b, recB); fNToRecFN#(expWidth, sigWidth) fNToRecFN_expectOut(expectOut, recExpectOut); /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ wire [formatWidth:0] recOut; wire [4:0] exceptionFlags; addRecFN#(expWidth, sigWidth) addRecFN_sub( control, 1'b1, recA, recB, roundingMode, recOut, exceptionFlags); /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ wire sameOut; sameRecFN#(expWidth, sigWidth) sameRecFN(recOut, recExpectOut, sameOut); /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ integer errorCount, count, partialCount; initial begin /*-------------------------------------------------------------------- *--------------------------------------------------------------------*/ $fwrite('h80000002, "Testing 'addRecF%0d_sub'", formatWidth); if ($fscanf('h80000000, "%h %h", control, roundingMode) < 2) begin $fdisplay('h80000002, ".\n--> Invalid test-cases input."); `finish_fail; end $fdisplay( 'h80000002, ", control %H, rounding mode %0d:", control, roundingMode ); /*-------------------------------------------------------------------- *--------------------------------------------------------------------*/ errorCount = 0; count = 0; partialCount = 0; begin :TestLoop while ( $fscanf( 'h80000000, "%h %h %h %h", a, b, expectOut, expectExceptionFlags ) == 4 ) begin #1; partialCount = partialCount + 1; if (partialCount == 10000) begin count = count + 10000; $fdisplay('h80000002, "%0d...", count); partialCount = 0; end if ( !sameOut || (exceptionFlags !== expectExceptionFlags) ) begin if (errorCount == 0) begin $display( "Errors found in 'addRecF%0d_sub', control %H, rounding mode %0d:", formatWidth, control, roundingMode ); end $write("%H %H", recA, recB); if (formatWidth > 64) begin $write("\n\t"); end else begin $write(" "); end $write("=> %H %H", recOut, exceptionFlags); if (formatWidth > 32) begin $write("\n\t"); end else begin $write(" "); end $display( "expected %H %H", recExpectOut, expectExceptionFlags); errorCount = errorCount + 1; if (errorCount == maxNumErrors) disable TestLoop; end #1; end end count = count + partialCount; /*-------------------------------------------------------------------- *--------------------------------------------------------------------*/ if (errorCount) begin $fdisplay( 'h80000002, "--> In %0d tests, %0d errors found.", count, errorCount ); `finish_fail; end else if (count == 0) begin $fdisplay('h80000002, "--> Invalid test-cases input."); `finish_fail; end else begin $display( "In %0d tests, no errors found in 'addRecF%0d_sub', control %H, rounding mode %0d.", count, formatWidth, control, roundingMode ); end /*-------------------------------------------------------------------- *--------------------------------------------------------------------*/ $finish; end endmodule /*---------------------------------------------------------------------------- *----------------------------------------------------------------------------*/ module test_addRecF16_sub; test_addRecFN_sub#(5, 11) test_addRecF16_sub(); endmodule module test_addRecF32_sub; test_addRecFN_sub#(8, 24) test_addRecF32_sub(); endmodule module test_addRecF64_sub; test_addRecFN_sub#(11, 53) test_addRecF64_sub(); endmodule module test_addRecF128_sub; test_addRecFN_sub#(15, 113) test_addRecF128_sub(); endmodule
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HS__AND2_BEHAVIORAL_PP_V `define SKY130_FD_SC_HS__AND2_BEHAVIORAL_PP_V /** * and2: 2-input AND. * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none // Import sub cells. `include "../u_vpwr_vgnd/sky130_fd_sc_hs__u_vpwr_vgnd.v" `celldefine module sky130_fd_sc_hs__and2 ( VPWR, VGND, X , A , B ); // Module ports input VPWR; input VGND; output X ; input A ; input B ; // Local signals wire and0_out_X ; wire u_vpwr_vgnd0_out_X; // Name Output Other arguments and and0 (and0_out_X , A, B ); sky130_fd_sc_hs__u_vpwr_vgnd u_vpwr_vgnd0 (u_vpwr_vgnd0_out_X, and0_out_X, VPWR, VGND); buf buf0 (X , u_vpwr_vgnd0_out_X ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_HS__AND2_BEHAVIORAL_PP_V
// ========== Copyright Header Begin ========================================== // // OpenSPARC T1 Processor File: sparc_ifu_swpla.v // Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES. // // The above named program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public // License version 2 as published by the Free Software Foundation. // // The above named program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this work; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. // // ========== Copyright Header End ============================================ //////////////////////////////////////////////////////////////////////// /* // Module Name: sparc_ifu_lfsr5 // Description: // The IFQ is the icache input queue. This communicates between the // IFU and the outside world. It handles icache misses and // invalidate requests from the crossbar. */ //////////////////////////////////////////////////////////////////////// module sparc_ifu_swpla(/*AUTOARG*/ // Outputs out, // Inputs in ); input [31:0] in; output out; wire [31:0] in; reg out; always @ (in) begin if (in[31:30] == 2'b01) // call out = 1'b1; else if (in[31:30] == 2'b00) // branch, sethi, nop begin if (in[24:22] == 3'b100) // nop/sethi out = 1'b0; else // branch out = 1'b1; end // if (in[31:30] == 2'b00) else if (in[31:30] == 2'b10) // arith, shift, mem#, mov begin if (in[24:23] == 2'b11) // wrpr, vis, save, jmpl out = 1'b1; else if (in[24] == 1'b0) // arith begin if (in[22] == 1'b0) // alu op out = 1'b0; else if ((in[22] == 1'b1) && (in[20:19] == 2'b00)) // subc or addc out = 1'b0; else // mul, div out = 1'b1; end // if (in[24] == 1'b0) else // if (in[24:23] == 2'b10) shft, mov, rdpr, tag begin if (in[22:19] == 4'h4) // mulscc out = 1'b1; else if (in[22] == 1'b0) // shft, tag out = 1'b0; else if ((in[22:19] == 4'hc) || (in[22:19] == 4'hf)) // mov out = 1'b0; // else if (in[22:19] == 4'ha) // rdpr // out = 1'b0; else // rdsr, mem#, popc, flushw, rdpr out = 1'b1; end // if ((in[24] == 1'b1) && (in[23] == 1'b0)) end // if (in[31:30] == 2'b10) else // ld st begin // if (in[24] & in[22] & in[21] & ~in[20] & in[19]) // prefetch // out = 1'b0; if (in[24] | in[23] | ~in[21]) // fp, alt space or ld out = 1'b1; // else if (in[24]) // FP and CAS // out = 1'b1; // else if (in[23] & in[20] & in[19]) // stda // out = 1'b1; else if ((~in[23]) && (in[22:19] == 4'he)) // stx out = 1'b0; else if (in[22:21] == 2'b01) // other st out = 1'b0; else // other atomic out = 1'b1; end // else: !if(in[31:30] == 2'b10) end // always @ (in) sink #(32) s0(.in (in)); endmodule // sparc_ifu_swpla
#include <bits/stdc++.h> using namespace std; long long n, memo[100001]; vector<long long> a; long long x; long long rek(int pos) { long long &ret = memo[pos]; if (ret != -1) return ret; ret = rek(pos - 1) + 20; x = upper_bound(a.begin(), a.end(), a[pos] - 90) - a.begin(); if (x) ret = min(ret, rek(x - 1) + 50); else ret = min(ret, 50LL); x = upper_bound(a.begin(), a.end(), a[pos] - 1440) - a.begin(); if (x) ret = min(ret, rek(x - 1) + 120); else ret = min(ret, 120LL); return ret; } int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> x; a.push_back(x); } memset(memo, -1, sizeof(memo)); memo[0] = 20; rek(n - 1); for (int i = 0; i < n; i++) if (!i) cout << memo[i] << endl; else cout << memo[i] - memo[i - 1] << endl; }
#include <bits/stdc++.h> using namespace std; int n, q; int b[100000][2]; int a[100000]; int c[5]; int main() { cin >> n >> q; for (int i = 0; i < n; i++) { b[i][0] = 0; b[i][1] = 0; a[i] = 0; } c[0] = n - 1; int s = 0; for (int i = 0; i < q; i++) { int y, x; cin >> x >> y; x--; y--; if (b[y][x] == 1) { if (y == 0) { if (b[y + 1][x] == 1) s--; c[a[y]]--; a[y]--; c[a[y]]++; } else if (y == n - 1) { if (b[y - 1][x] == 1) s--; c[a[y - 1]]--; a[y - 1]--; c[a[y - 1]]++; } else { if (b[y - 1][x] == 1) s--; if (b[y + 1][x] == 1) s--; c[a[y - 1]]--; a[y - 1]--; c[a[y - 1]]++; c[a[y]]--; a[y]--; c[a[y]]++; } b[y][x] = 0; } else { if (y == 0) { if (b[y + 1][x] == 1) s++; c[a[y]]--; a[y]++; c[a[y]]++; } else if (y == n - 1) { if (b[y - 1][x] == 1) s++; c[a[y - 1]]--; a[y - 1]++; c[a[y - 1]]++; } else { if (b[y + 1][x] == 1) s++; if (b[y - 1][x] == 1) s++; c[a[y - 1]]--; a[y - 1]++; c[a[y - 1]]++; c[a[y]]--; a[y]++; c[a[y]]++; } b[y][x] = 1; } if (c[4] == 0 && c[3] == 0 && c[2] - s <= 0) cout << Yes << endl; else cout << No << endl; } }
// megafunction wizard: %FIFO% // GENERATION: STANDARD // VERSION: WM1.0 // MODULE: dcfifo // ============================================================ // File Name: fifo_uart.v // Megafunction Name(s): // dcfifo // // Simulation Library Files(s): // altera_mf // ============================================================ // ************************************************************ // THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE! // // 12.1 Build 243 01/31/2013 SP 1 SJ Web Edition // ************************************************************ //Copyright (C) 1991-2012 Altera Corporation //Your use of Altera Corporation's design tools, logic functions //and other software and tools, and its AMPP partner logic //functions, and any output files from any of the foregoing //(including device programming or simulation files), and any //associated documentation or information are expressly subject //to the terms and conditions of the Altera Program License //Subscription Agreement, Altera MegaCore Function License //Agreement, or other applicable license agreement, including, //without limitation, that your use is for the sole purpose of //programming logic devices manufactured by Altera and sold by //Altera or its authorized distributors. Please refer to the //applicable agreement for further details. // synopsys translate_off `timescale 1 ps / 1 ps // synopsys translate_on module fifo_uart ( aclr, data, rdclk, rdreq, wrclk, wrreq, q, rdempty, wrfull); input aclr; input [7:0] data; input rdclk; input rdreq; input wrclk; input wrreq; output [7:0] q; output rdempty; output wrfull; `ifndef ALTERA_RESERVED_QIS // synopsys translate_off `endif tri0 aclr; `ifndef ALTERA_RESERVED_QIS // synopsys translate_on `endif wire sub_wire0; wire [7:0] sub_wire1; wire sub_wire2; wire wrfull = sub_wire0; wire [7:0] q = sub_wire1[7:0]; wire rdempty = sub_wire2; dcfifo dcfifo_component ( .rdclk (rdclk), .wrclk (wrclk), .wrreq (wrreq), .aclr (aclr), .data (data), .rdreq (rdreq), .wrfull (sub_wire0), .q (sub_wire1), .rdempty (sub_wire2), .rdfull (), .rdusedw (), .wrempty (), .wrusedw ()); defparam dcfifo_component.intended_device_family = "Cyclone IV E", dcfifo_component.lpm_numwords = 4096, dcfifo_component.lpm_showahead = "OFF", dcfifo_component.lpm_type = "dcfifo", dcfifo_component.lpm_width = 8, dcfifo_component.lpm_widthu = 12, dcfifo_component.overflow_checking = "ON", dcfifo_component.rdsync_delaypipe = 5, dcfifo_component.read_aclr_synch = "OFF", dcfifo_component.underflow_checking = "ON", dcfifo_component.use_eab = "ON", dcfifo_component.write_aclr_synch = "OFF", dcfifo_component.wrsync_delaypipe = 5; endmodule // ============================================================ // CNX file retrieval info // ============================================================ // Retrieval info: PRIVATE: AlmostEmpty NUMERIC "0" // Retrieval info: PRIVATE: AlmostEmptyThr NUMERIC "-1" // Retrieval info: PRIVATE: AlmostFull NUMERIC "0" // Retrieval info: PRIVATE: AlmostFullThr NUMERIC "-1" // Retrieval info: PRIVATE: CLOCKS_ARE_SYNCHRONIZED NUMERIC "0" // Retrieval info: PRIVATE: Clock NUMERIC "4" // Retrieval info: PRIVATE: Depth NUMERIC "4096" // Retrieval info: PRIVATE: Empty NUMERIC "1" // Retrieval info: PRIVATE: Full NUMERIC "1" // Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Cyclone IV E" // Retrieval info: PRIVATE: LE_BasedFIFO NUMERIC "0" // Retrieval info: PRIVATE: LegacyRREQ NUMERIC "1" // Retrieval info: PRIVATE: MAX_DEPTH_BY_9 NUMERIC "0" // Retrieval info: PRIVATE: OVERFLOW_CHECKING NUMERIC "0" // Retrieval info: PRIVATE: Optimize NUMERIC "2" // Retrieval info: PRIVATE: RAM_BLOCK_TYPE NUMERIC "0" // Retrieval info: PRIVATE: SYNTH_WRAPPER_GEN_POSTFIX STRING "0" // Retrieval info: PRIVATE: UNDERFLOW_CHECKING NUMERIC "0" // Retrieval info: PRIVATE: UsedW NUMERIC "1" // Retrieval info: PRIVATE: Width NUMERIC "8" // Retrieval info: PRIVATE: dc_aclr NUMERIC "1" // Retrieval info: PRIVATE: diff_widths NUMERIC "0" // Retrieval info: PRIVATE: msb_usedw NUMERIC "0" // Retrieval info: PRIVATE: output_width NUMERIC "8" // Retrieval info: PRIVATE: rsEmpty NUMERIC "1" // Retrieval info: PRIVATE: rsFull NUMERIC "0" // Retrieval info: PRIVATE: rsUsedW NUMERIC "0" // Retrieval info: PRIVATE: sc_aclr NUMERIC "0" // Retrieval info: PRIVATE: sc_sclr NUMERIC "0" // Retrieval info: PRIVATE: wsEmpty NUMERIC "0" // Retrieval info: PRIVATE: wsFull NUMERIC "1" // Retrieval info: PRIVATE: wsUsedW NUMERIC "0" // Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all // Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "Cyclone IV E" // Retrieval info: CONSTANT: LPM_NUMWORDS NUMERIC "4096" // Retrieval info: CONSTANT: LPM_SHOWAHEAD STRING "OFF" // Retrieval info: CONSTANT: LPM_TYPE STRING "dcfifo" // Retrieval info: CONSTANT: LPM_WIDTH NUMERIC "8" // Retrieval info: CONSTANT: LPM_WIDTHU NUMERIC "12" // Retrieval info: CONSTANT: OVERFLOW_CHECKING STRING "ON" // Retrieval info: CONSTANT: RDSYNC_DELAYPIPE NUMERIC "5" // Retrieval info: CONSTANT: READ_ACLR_SYNCH STRING "OFF" // Retrieval info: CONSTANT: UNDERFLOW_CHECKING STRING "ON" // Retrieval info: CONSTANT: USE_EAB STRING "ON" // Retrieval info: CONSTANT: WRITE_ACLR_SYNCH STRING "OFF" // Retrieval info: CONSTANT: WRSYNC_DELAYPIPE NUMERIC "5" // Retrieval info: USED_PORT: aclr 0 0 0 0 INPUT GND "aclr" // Retrieval info: USED_PORT: data 0 0 8 0 INPUT NODEFVAL "data[7..0]" // Retrieval info: USED_PORT: q 0 0 8 0 OUTPUT NODEFVAL "q[7..0]" // Retrieval info: USED_PORT: rdclk 0 0 0 0 INPUT NODEFVAL "rdclk" // Retrieval info: USED_PORT: rdempty 0 0 0 0 OUTPUT NODEFVAL "rdempty" // Retrieval info: USED_PORT: rdreq 0 0 0 0 INPUT NODEFVAL "rdreq" // Retrieval info: USED_PORT: wrclk 0 0 0 0 INPUT NODEFVAL "wrclk" // Retrieval info: USED_PORT: wrfull 0 0 0 0 OUTPUT NODEFVAL "wrfull" // Retrieval info: USED_PORT: wrreq 0 0 0 0 INPUT NODEFVAL "wrreq" // Retrieval info: CONNECT: @aclr 0 0 0 0 aclr 0 0 0 0 // Retrieval info: CONNECT: @data 0 0 8 0 data 0 0 8 0 // Retrieval info: CONNECT: @rdclk 0 0 0 0 rdclk 0 0 0 0 // Retrieval info: CONNECT: @rdreq 0 0 0 0 rdreq 0 0 0 0 // Retrieval info: CONNECT: @wrclk 0 0 0 0 wrclk 0 0 0 0 // Retrieval info: CONNECT: @wrreq 0 0 0 0 wrreq 0 0 0 0 // Retrieval info: CONNECT: q 0 0 8 0 @q 0 0 8 0 // Retrieval info: CONNECT: rdempty 0 0 0 0 @rdempty 0 0 0 0 // Retrieval info: CONNECT: wrfull 0 0 0 0 @wrfull 0 0 0 0 // Retrieval info: GEN_FILE: TYPE_NORMAL fifo_uart.v TRUE // Retrieval info: GEN_FILE: TYPE_NORMAL fifo_uart.inc FALSE // Retrieval info: GEN_FILE: TYPE_NORMAL fifo_uart.cmp FALSE // Retrieval info: GEN_FILE: TYPE_NORMAL fifo_uart.bsf FALSE // Retrieval info: GEN_FILE: TYPE_NORMAL fifo_uart_inst.v TRUE // Retrieval info: GEN_FILE: TYPE_NORMAL fifo_uart_bb.v TRUE // Retrieval info: LIB_FILE: altera_mf
#include <bits/stdc++.h> using namespace std; long long n; int main() { ios_base::sync_with_stdio(false); cin >> n; cout << (n - 3) * (n - 1) + 1; return 0; }
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_LS__HA_1_V `define SKY130_FD_SC_LS__HA_1_V /** * ha: Half adder. * * Verilog wrapper for ha with size of 1 units. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none `include "sky130_fd_sc_ls__ha.v" `ifdef USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_ls__ha_1 ( COUT, SUM , A , B , VPWR, VGND, VPB , VNB ); output COUT; output SUM ; input A ; input B ; input VPWR; input VGND; input VPB ; input VNB ; sky130_fd_sc_ls__ha base ( .COUT(COUT), .SUM(SUM), .A(A), .B(B), .VPWR(VPWR), .VGND(VGND), .VPB(VPB), .VNB(VNB) ); endmodule `endcelldefine /*********************************************************/ `else // If not USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_ls__ha_1 ( COUT, SUM , A , B ); output COUT; output SUM ; input A ; input B ; // Voltage supply signals supply1 VPWR; supply0 VGND; supply1 VPB ; supply0 VNB ; sky130_fd_sc_ls__ha base ( .COUT(COUT), .SUM(SUM), .A(A), .B(B) ); endmodule `endcelldefine /*********************************************************/ `endif // USE_POWER_PINS `default_nettype wire `endif // SKY130_FD_SC_LS__HA_1_V
// Accellera Standard V2.3 Open Verification Library (OVL). // Accellera Copyright (c) 2005-2008. All rights reserved. `include "std_ovl_defines.h" `module ovl_one_hot (clock, reset, enable, test_expr, fire); parameter severity_level = `OVL_SEVERITY_DEFAULT; parameter width = 32; parameter property_type = `OVL_PROPERTY_DEFAULT; parameter msg = `OVL_MSG_DEFAULT; parameter coverage_level = `OVL_COVER_DEFAULT; parameter clock_edge = `OVL_CLOCK_EDGE_DEFAULT; parameter reset_polarity = `OVL_RESET_POLARITY_DEFAULT; parameter gating_type = `OVL_GATING_TYPE_DEFAULT; input clock, reset, enable; input [width-1:0] test_expr; output [`OVL_FIRE_WIDTH-1:0] fire; // Parameters that should not be edited parameter assert_name = "OVL_ONE_HOT"; `include "std_ovl_reset.h" `include "std_ovl_clock.h" `include "std_ovl_cover.h" `include "std_ovl_task.h" `include "std_ovl_init.h" `ifdef OVL_VERILOG `include "./vlog95/ovl_one_hot_logic.v" `endif `ifdef OVL_SVA `include "./sva05/ovl_one_hot_logic.sv" `endif `ifdef OVL_PSL `include "./psl05/assert_one_hot_psl_logic.v" `else assign fire = {fire_cover, fire_xcheck, fire_2state}; `endmodule // ovl_one_hot `endif
#include <bits/stdc++.h> using namespace std; int one, two, three, four; bool check(deque<int> x) { int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0; for (int i = 0; i < x.size(); i++) { if (x[i] == 0) cnt1++; if (x[i] == 1) cnt2++; if (x[i] == 2) cnt3++; if (x[i] == 3) cnt4++; } if (cnt1 == one && cnt2 == two && cnt3 == three & cnt4 == four) { for (int i = 0; i + 1 < x.size(); i++) { if (abs(x[i] - x[i + 1]) != 1) return 0; } cout << YES << n ; for (int i : x) cout << i << ; exit(0); } return 0; } deque<int> merge(deque<int> x, deque<int> y) { for (int i : y) x.push_back(i); return x; } void go2(pair<int, int> a, pair<int, int> b, deque<int> ans) { deque<int> ans2 = ans; if (a.first < b.first) { for (int i = 0; i < a.first; i++) { ans.push_back(b.second); ans.push_back(a.second); } ans.push_back(b.second); } else { for (int i = 0; i < b.first; i++) { ans.push_back(a.second); ans.push_back(b.second); } if (a.first != b.first) ans.push_back(a.second); } check(ans); ans = ans2; if (a.first <= b.first) { for (int i = 0; i < a.first; i++) { ans.push_back(b.second); ans.push_back(a.second); } if (a.first != b.first) ans.push_back(b.second); } else { for (int i = 0; i < b.first; i++) { ans.push_back(a.second); ans.push_back(b.second); } if (a.first != b.first) ans.push_back(a.second); } ans = ans2; deque<int> zl; if (a.first < b.first) { for (int i = 0; i < a.first; i++) { zl.push_back(b.second); zl.push_back(a.second); } zl.push_back(b.second); } else { for (int i = 0; i < b.first; i++) { zl.push_back(a.second); zl.push_back(b.second); } if (a.first != b.first) zl.push_back(a.second); } check(merge(zl, ans)); zl.clear(); if (a.first <= b.first) { for (int i = 0; i < a.first; i++) { zl.push_back(b.second); zl.push_back(a.second); } if (a.first != b.first) zl.push_back(b.second); } else { for (int i = 0; i < b.first; i++) { zl.push_back(a.second); zl.push_back(b.second); } if (a.first != b.first) zl.push_back(a.second); } check(merge(zl, ans)); } void go3(pair<int, int> a, pair<int, int> b, pair<int, int> c, deque<int> cur) { deque<int> ans; if (a.first <= b.first) { for (int i = 0; i < a.first; i++) { ans.push_back(a.second); ans.push_back(b.second); } go2(pair<int, int>(b.first - a.first, b.second), c, merge(cur, ans)); go2(pair<int, int>(b.first - a.first, b.second), c, merge(ans, cur)); ans.clear(); for (int i = 0; i < a.first; i++) { ans.push_back(b.second); ans.push_back(a.second); } go2(pair<int, int>(b.first - a.first, b.second), c, merge(cur, ans)); go2(pair<int, int>(b.first - a.first, b.second), c, merge(ans, cur)); } ans.clear(); if (c.first <= b.first) { for (int i = 0; i < c.first; i++) { ans.push_back(c.second); ans.push_back(b.second); } go2(a, pair<int, int>(b.first - c.first, b.second), merge(cur, ans)); go2(a, pair<int, int>(b.first - c.first, b.second), merge(ans, cur)); ans.clear(); for (int i = 0; i < c.first; i++) { ans.push_back(b.second); ans.push_back(c.second); } go2(a, pair<int, int>(b.first - c.first, b.second), merge(cur, ans)); go2(a, pair<int, int>(b.first - c.first, b.second), merge(ans, cur)); } } void go4(int a, int b, int c, int d) { if (a <= b) { deque<int> lul; for (int i = 0; i < a; i++) { lul.push_back(0); lul.push_back(1); } go3(pair<int, int>(b - a, 1), pair<int, int>(c, 2), pair<int, int>(d, 3), lul); lul.clear(); for (int i = 0; i < a; i++) { lul.push_back(1); lul.push_back(0); } go3(pair<int, int>(b - a, 1), pair<int, int>(c, 2), pair<int, int>(d, 3), lul); } if (d <= c) { deque<int> lul; for (int i = 0; i < d; i++) { lul.push_back(3); lul.push_back(2); } go3(pair<int, int>(a, 0), pair<int, int>(b, 1), pair<int, int>(c - d, 2), lul); lul.clear(); for (int i = 0; i < d; i++) { lul.push_back(2); lul.push_back(3); } go3(pair<int, int>(a, 0), pair<int, int>(b, 1), pair<int, int>(c - d, 2), lul); } } int main() { cin >> one >> two >> three >> four; go4(one, two, three, four); cout << NO ; return 0; }
module xortest(out, a, b); output out; input a, b; parameter tdelay=2; wire a_, b_, i1, i2, i3; supply0 gnd; supply1 vdd; nmos #(tdelay) n5(a_, gnd, a); pmos #(tdelay) p5(a_, vdd, a); nmos #(tdelay) n6(b_, gnd, b); pmos #(tdelay) p6(b_, vdd, b); nmos #(tdelay) n1(out, i1, a); nmos #(tdelay) n2(i1, gnd, b); nmos #(tdelay) n3(out, i2, a_); nmos #(tdelay) n4(i2, gnd, b_); pmos #(tdelay) p1(out, i3, a); pmos #(tdelay) p2(out, i3, b); pmos #(tdelay) p3(i3, vdd, a_); pmos #(tdelay) p4(i3, vdd, b_); endmodule module testXor(); wire out; reg a, b; reg pass; xortest x1(out, a, b); initial begin pass = 1'b1; a=1;b=1; #100; $display("A=%b B=%b Out=%b",a,b,out); a=0;b=1; #100; $display("A=%b B=%b Out=%b",a,b,out); a=1;b=0; #100; $display("A=%b B=%b Out=%b",a,b,out); a=0;b=0; #100; $display("A=%b B=%b Out=%b",a,b,out); repeat (3) begin a=0;b=1; #100; $display("REP A=%b B=%b Out=%b",a,b,out); a=1;b=0; #100; $display("REP A=%b B=%b Out=%b",a,b,out); end a=1;b=1; #100; $display("A=%b B=%b Out=%b",a,b,out); a=0;b=1; #100; $display("A=%b B=%b Out=%b",a,b,out); a=1;b=0; #100; $display("A=%b B=%b Out=%b",a,b,out); a=0;b=0; #100; $display("A=%b B=%b Out=%b",a,b,out); if (pass) $display("PASSED"); end always @(out) begin // Wait for the value to settle. #10 if (out !== (a ^ b)) begin $display("Failed at %0t, expected %b, got %b, with a=%b, b=%b", $time, a ^ b, out, a, b); pass = 1'b0; end end endmodule
`timescale 1ns / 1ps ////////////////////////////////////////////////////////////////////////////////// // Company: // Engineer: // // Create Date: 19:02:19 01/29/2015 // Design Name: // Module Name: vga_bsprite // Project Name: // Target Devices: // Tool versions: // Description: // // Dependencies: // // Revision: // Revision 0.01 - File Created // Additional Comments: // ////////////////////////////////////////////////////////////////////////////////// module vga_bsprite( input wire vidon, input wire [9:0]hc, input wire [9:0]vc, input wire [7:0]M, //input wire [3:0]mine_state_single, input wire [3:0]posx, input wire [3:0]posy, //input wire [2:0]state, input wire [7:0]face, output wire [9:0]rom_addr26, output wire [7:0]rom_addr16, output reg[2:0]red, output reg[2:0]green, output reg[1:0]blue, output wire [3:0]C1, output wire [3:0]R1 ); parameter hbp=10'b0010010000; parameter vbp=10'b0000011111; parameter W=16; parameter H=16; wire [3:0]xpix,ypix; reg spriteon;//,R,G,B; wire [9:0]fx,fy; reg faceon; wire [19:0]addrface; assign C1=(hc-hbp-240)>>4; assign R1=(vc-vbp-200)>>4; assign ypix=vc-vbp-200-(R1<<4); assign xpix=hc-hbp-240-(C1<<4); assign rom_addr16={ypix,xpix}; assign fx=hc-hbp-307; assign fy=vc-vbp-174; assign addrface={1'b0,fy,4'b0000}+{2'b0,fy,3'b000}+{4'b0000,fy,1'b0}+{5'b00000,fx}; assign rom_addr26=addrface[9:0];//fy*26+fx;//{1'b0,fy,4'b0000}+{2'b0,fy,3'b000}+{4'b0000,fy,1'b0}+fx; always@(*) begin if (hc-hbp>=240 && hc-hbp<400 && vc-vbp>=200 && vc-vbp<360)//&&(hc>=C1<<4+hbp)&&(hc<C1<<4+hbp+W)&&(vc>=R1<<4+vbp)&&(vc<R1<<4+vbp+H)) spriteon=1; else spriteon=0; end always@(*) begin if(hc-hbp>=307 && hc-hbp<333 && vc-vbp>=174 && vc-vbp<200) faceon=1; else faceon=0; end always@(*) begin red=0; green=0; blue=0; if((spriteon==1)&&(vidon==1)) begin red=M[7:5]; green=M[4:2]; blue=M[1:0]; if(R1==posy && C1==posx) begin red=(red<7)?red+1:red; //green=(green<7)?green+1:green; //blue=(blue<4)?blue+1:blue; end end else if( (faceon==1) && (vidon==1) ) begin red=face[7:5]; green=face[4:2]; blue=face[1:0]; end end endmodule
// This file is part of multiexp-a5gx. // // multiexp-a5gx is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. `timescale 1 ns / 10 ps; module table_control_test (); reg clk; reg rstb; wire [26:0] tdata_0, tdata_1, tdata_2; reg [1:0] command; initial begin clk = 0; rstb = 0; command = 0; #1 rstb = 1; #8 command = 2'b01; #8 command = 0; #400 command = 2'b01; #8 command = 0; #104 command = 2'b11; #8 command = 0; #16 command = 2'b10; #8 command = 0; #8 command = 2'b01; #8 command = 0; end always @(clk) begin clk <= #4 ~clk; end table_control ictrl ( .clk (clk) , .ctrl_reset_n (rstb) , .tdatai ('0) , .twraddr ('0) , .twren ('0) , .tdata_0 (tdata_0) , .tdata_1 (tdata_1) , .tdata_2 (tdata_2) , .command (command) ); endmodule
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HS__DFRTP_BEHAVIORAL_PP_V `define SKY130_FD_SC_HS__DFRTP_BEHAVIORAL_PP_V /** * dfrtp: Delay flop, inverted reset, single output. * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none // Import sub cells. `include "../u_df_p_r_no_pg/sky130_fd_sc_hs__u_df_p_r_no_pg.v" `celldefine module sky130_fd_sc_hs__dfrtp ( VPWR , VGND , Q , CLK , D , RESET_B ); // Module ports input VPWR ; input VGND ; output Q ; input CLK ; input D ; input RESET_B; // Local signals wire buf_Q ; wire RESET ; reg notifier ; wire D_delayed ; wire RESET_B_delayed; wire CLK_delayed ; wire awake ; wire cond0 ; wire cond1 ; // Name Output Other arguments not not0 (RESET , RESET_B_delayed ); sky130_fd_sc_hs__u_df_p_r_no_pg u_df_p_r_no_pg0 (buf_Q , D_delayed, CLK_delayed, RESET, notifier, VPWR, VGND); assign awake = ( VPWR === 1'b1 ); assign cond0 = ( awake && ( RESET_B_delayed === 1'b1 ) ); assign cond1 = ( awake && ( RESET_B === 1'b1 ) ); buf buf0 (Q , buf_Q ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_HS__DFRTP_BEHAVIORAL_PP_V
#include <bits/stdc++.h> using namespace std; const int MOD = (int)1e9 + 7; const int MAX = 1e6; int len1, len2, pre[MAX], suf[MAX]; bool can_skip(int skip) { for (int i = 1; i + skip - 1 < len1; i++) if (pre[i - 1] + suf[i + skip] >= len2) return 1; return 0; } int main() { string x, y, z = 1 ; cin >> x >> y; z += x; x = z; len1 = x.length(); len2 = y.length(); for (int i = 1, j = 0, it = 0; i < len1; i++) { if (j < len2 && x[i] == y[j]) it++, j++; pre[i] = it; } for (int i = len1 - 1, j = len2 - 1, it = 0; i >= 1; i--) { if (j >= 0 && x[i] == y[j]) it++, j--; suf[i] = it; } int l = 0, r = len1, ans = 0; while (l <= r) { int mid = (l + r) >> 1; if (can_skip(mid)) { l = mid + 1, ans = mid; } else r = mid - 1; } cout << ans << endl; return 0; }
module MAX6682Mean ( (* intersynth_port="Reset_n_i" *) input Reset_n_i, (* intersynth_port="Clk_i" *) input Clk_i, (* intersynth_port="ReconfModuleIn_s", intersynth_conntype="Bit" *) input Enable_i, (* intersynth_port="ReconfModuleIRQs_s", intersynth_conntype="Bit" *) output reg CpuIntr_o, (* intersynth_port="Outputs_o", intersynth_conntype="Bit" *) output MAX6682CS_n_o, (* intersynth_port="SPI_DataOut", intersynth_conntype="Byte" *) input[7:0] SPI_Data_i, (* intersynth_port="SPI_Write", intersynth_conntype="Bit" *) output SPI_Write_o, (* intersynth_port="SPI_ReadNext", intersynth_conntype="Bit" *) output SPI_ReadNext_o, (* intersynth_port="SPI_DataIn", intersynth_conntype="Byte" *) output [7:0] SPI_Data_o, (* intersynth_port="SPI_FIFOFull", intersynth_conntype="Bit" *) input SPI_FIFOFull_i, (* intersynth_port="SPI_FIFOEmpty", intersynth_conntype="Bit" *) input SPI_FIFOEmpty_i, (* intersynth_port="SPI_Transmission", intersynth_conntype="Bit" *) input SPI_Transmission_i, (* intersynth_param="PauseCounterPreset_i", intersynth_conntype="Word" *) input[15:0] PauseCounterPreset_i, (* intersynth_param="PeriodCounterPresetH_i", intersynth_conntype="Word" *) input[15:0] PeriodCounterPresetH_i, (* intersynth_param="PeriodCounterPresetL_i", intersynth_conntype="Word" *) input[15:0] PeriodCounterPresetL_i, (* intersynth_param="SensorValue_o", intersynth_conntype="Word" *) output[15:0] SensorValue_o, (* intersynth_param="Threshold_i", intersynth_conntype="Word" *) input[15:0] Threshold_i, (* intersynth_port="SPI_CPOL", intersynth_conntype="Bit" *) output SPI_CPOL_o, (* intersynth_port="SPI_CPHA", intersynth_conntype="Bit" *) output SPI_CPHA_o, (* intersynth_port="SPI_LSBFE", intersynth_conntype="Bit" *) output SPI_LSBFE_o ); /* constant value for dynamic signal */ assign SPI_CPOL_o = 1'b0; /* constant value for dynamic signal */ assign SPI_CPHA_o = 1'b0; /* constant value for dynamic signal */ assign SPI_LSBFE_o = 1'b0; assign SPI_Data_o = 8'b00000000; reg SPI_FSM_Start; wire SPI_FSM_Done; wire [7:0] Byte0; wire [7:0] Byte1; SPI_FSM SPI_FSM_1 ( .Reset_n_i (Reset_n_i), .Clk_i (Clk_i), .SPI_FSM_Start (SPI_FSM_Start), .SPI_Transmission_i (SPI_Transmission_i), .MAX6682CS_n_o (MAX6682CS_n_o), .SPI_Write_o (SPI_Write_o), .SPI_ReadNext_o (SPI_ReadNext_o), .SPI_FSM_Done (SPI_FSM_Done), .SPI_Data_i (SPI_Data_i), .Byte0 (Byte0), .Byte1 (Byte1) ); ///////////////////////////////////////////////////////////////////////////// // SensorFSM //////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Sensor FSM localparam stDisabled = 4'd0; localparam stIdle = 4'd1; localparam stSPI_Xfer1 = 4'd2; localparam stSPI_Pause1 = 4'd3; localparam stSPI_Xfer2 = 4'd4; localparam stSPI_Pause2 = 4'd5; localparam stSPI_Xfer3 = 4'd6; localparam stSPI_Pause3 = 4'd7; localparam stSPI_Xfer4 = 4'd8; localparam stCompare = 4'd9; reg [3:0] SensorFSM_State; reg [3:0] SensorFSM_NextState; reg PauseTimerPreset; reg PauseTimerEnable; wire PauseTimerOvfl; wire SensorFSM_TimerOvfl; reg SensorFSM_TimerPreset; reg SensorFSM_TimerEnable; wire SensorFSM_DiffTooLarge; reg SensorFSM_StoreValue; // store value received from sensor to accumulator reg SensorFSM_AddValue; // add value received from sensor to accumulator reg SensorFSM_StoreNewValue; // store accumulator as new value always @(negedge Reset_n_i or posedge Clk_i) begin if (!Reset_n_i) begin SensorFSM_State <= stDisabled; end else begin // rising clock edge // state register SensorFSM_State <= SensorFSM_NextState; end end always @(SensorFSM_State, Enable_i, SensorFSM_TimerOvfl, SPI_FSM_Done, PauseTimerOvfl, SensorFSM_DiffTooLarge) begin // process SensorFSM_CombProc SensorFSM_NextState = SensorFSM_State; // control signal default values SensorFSM_TimerPreset = 1'b1; SensorFSM_TimerEnable = 1'b0; PauseTimerPreset = 1'b1; PauseTimerEnable = 1'b0; SPI_FSM_Start = 1'b0; SensorFSM_StoreValue = 1'b0; SensorFSM_AddValue = 1'b0; SensorFSM_StoreNewValue = 1'b0; CpuIntr_o = 1'b0; // next state and output logic case (SensorFSM_State) stDisabled: begin if (Enable_i == 1'b1) begin SensorFSM_NextState = stIdle; SensorFSM_TimerPreset = 1'b0; SensorFSM_TimerEnable = 1'b1; // start timer end end stIdle: begin SensorFSM_TimerPreset = 1'b0; SensorFSM_TimerEnable = 1'b1; // timer running if (Enable_i == 1'b0) begin SensorFSM_NextState = stDisabled; end else if (SensorFSM_TimerOvfl == 1'b1) begin SensorFSM_NextState = stSPI_Xfer1; SPI_FSM_Start = 1'b1; end end stSPI_Xfer1: begin if (SPI_FSM_Done == 1'b1) begin SensorFSM_NextState = stSPI_Pause1; SensorFSM_StoreValue = 1'b1; // store value PauseTimerPreset = 1'b0; PauseTimerEnable = 1'b1; end end stSPI_Pause1: begin PauseTimerPreset = 1'b0; PauseTimerEnable = 1'b1; if (PauseTimerOvfl == 1'b1) begin SensorFSM_NextState = stSPI_Xfer2; SPI_FSM_Start = 1'b1; end end stSPI_Xfer2: begin if (SPI_FSM_Done == 1'b1) begin SensorFSM_NextState = stSPI_Pause2; SensorFSM_AddValue = 1'b1; // add value PauseTimerPreset = 1'b0; PauseTimerEnable = 1'b1; end end stSPI_Pause2: begin PauseTimerPreset = 1'b0; PauseTimerEnable = 1'b1; if (PauseTimerOvfl == 1'b1) begin SensorFSM_NextState = stSPI_Xfer3; SPI_FSM_Start = 1'b1; end end stSPI_Xfer3: begin if (SPI_FSM_Done == 1'b1) begin SensorFSM_NextState = stSPI_Pause3; SensorFSM_AddValue = 1'b1; // add value PauseTimerPreset = 1'b0; PauseTimerEnable = 1'b1; end end stSPI_Pause3: begin PauseTimerPreset = 1'b0; PauseTimerEnable = 1'b1; if (PauseTimerOvfl == 1'b1) begin SensorFSM_NextState = stSPI_Xfer4; SPI_FSM_Start = 1'b1; end end stSPI_Xfer4: begin if (SPI_FSM_Done == 1'b1) begin SensorFSM_NextState = stCompare; SensorFSM_AddValue = 1'b1; // add value end end stCompare: begin SensorFSM_NextState = stIdle; if (SensorFSM_DiffTooLarge == 1'b1) begin SensorFSM_StoreNewValue = 1'b1; // store new value CpuIntr_o = 1'b1; // notify CPU end end default: begin end endcase end ///////////////////////////////////////////////////////////////////////////// // Word Arithmetic ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Pause Timer ////////////////////////////////////////////////////////////// reg [15:0] PauseTimer; always @(negedge Reset_n_i or posedge Clk_i) begin if (!Reset_n_i) begin PauseTimer <= 16'd0; end else begin if (PauseTimerPreset) begin PauseTimer <= PauseCounterPreset_i; end else if (PauseTimerEnable) begin PauseTimer <= PauseTimer - 1'd1; end end end assign PauseTimerOvfl = (PauseTimer == 0) ? 1'b1 : 1'b0; // Periode Timer //////////////////////////////////////////////////////////// reg [31:0] SensorFSM_Timer; always @(negedge Reset_n_i or posedge Clk_i) begin if (!Reset_n_i) begin SensorFSM_Timer <= 32'd0; end else begin if (SensorFSM_TimerPreset) begin SensorFSM_Timer <= {PeriodCounterPresetH_i, PeriodCounterPresetL_i}; end else if (SensorFSM_TimerEnable) begin SensorFSM_Timer <= SensorFSM_Timer - 1'd1; end end end assign SensorFSM_TimerOvfl = (SensorFSM_Timer == 0) ? 1'b1 : 1'b0; ///////////////////////////////////////////////////////////////////////////// // Word Arithmetic // interconnecting signals wire [15:0] SensorValue; reg [15:0] Accumulator; reg [15:0] LastValue; wire [15:0] AbsDiffResult; assign SensorValue = { 5'b00000, Byte1, Byte0[7:5] }; always @(negedge Reset_n_i or posedge Clk_i) begin if (!Reset_n_i) begin Accumulator <= 16'd0; LastValue <= 16'd0; end else begin // accumulate measurements if (SensorFSM_StoreValue) begin Accumulator <= SensorValue; end else if (SensorFSM_AddValue) begin Accumulator <= Accumulator + SensorValue; end // store accumulated sum if (SensorFSM_StoreNewValue) begin LastValue <= Accumulator; end end end wire [16:0] DiffAB; wire [15:0] DiffBA; assign DiffAB = {1'b0, LastValue} - {1'b0, Accumulator}; assign DiffBA = Accumulator - LastValue; assign AbsDiffResult = DiffAB[16] ? DiffBA : DiffAB[15:0]; assign SensorFSM_DiffTooLarge = (AbsDiffResult > Threshold_i) ? 1'b1 : 1'b0; assign SensorValue_o = LastValue; endmodule
/* * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HS__CLKDLYINV5SD1_FUNCTIONAL_V `define SKY130_FD_SC_HS__CLKDLYINV5SD1_FUNCTIONAL_V /** * clkdlyinv5sd1: Clock Delay Inverter 5-stage 0.15um length inner * stage gate. * * Verilog simulation functional model. */ `timescale 1ns / 1ps `default_nettype none // Import sub cells. `include "../u_vpwr_vgnd/sky130_fd_sc_hs__u_vpwr_vgnd.v" `celldefine module sky130_fd_sc_hs__clkdlyinv5sd1 ( Y , A , VPWR, VGND ); // Module ports output Y ; input A ; input VPWR; input VGND; // Local signals wire not0_out_Y ; wire u_vpwr_vgnd0_out_Y; // Name Output Other arguments not not0 (not0_out_Y , A ); sky130_fd_sc_hs__u_vpwr_vgnd u_vpwr_vgnd0 (u_vpwr_vgnd0_out_Y, not0_out_Y, VPWR, VGND); buf buf0 (Y , u_vpwr_vgnd0_out_Y ); endmodule `endcelldefine `default_nettype wire `endif // SKY130_FD_SC_HS__CLKDLYINV5SD1_FUNCTIONAL_V
//----------------------------------------------------------------------------- // Pretend to be an ISO 14443 tag. We will do this by alternately short- // circuiting and open-circuiting the antenna coil, with the tri-state // pins. // // We communicate over the SSP, as a bitstream (i.e., might as well be // unframed, though we still generate the word sync signal). The output // (ARM -> FPGA) tells us whether to modulate or not. The input (FPGA // -> ARM) is us using the A/D as a fancy comparator; this is with // (software-added) hysteresis, to undo the high-pass filter. // // At this point only Type A is implemented. This means that we are using a // bit rate of 106 kbit/s, or fc/128. Oversample by 4, which ought to make // things practical for the ARM (fc/32, 423.8 kbits/s, ~50 kbytes/s) // // Jonathan Westhues, October 2006 //----------------------------------------------------------------------------- module hi_simulate( ck_1356meg, pwr_lo, pwr_hi, pwr_oe1, pwr_oe2, pwr_oe3, pwr_oe4, adc_d, adc_clk, ssp_frame, ssp_din, ssp_dout, ssp_clk, dbg, mod_type ); input ck_1356meg; output pwr_lo, pwr_hi, pwr_oe1, pwr_oe2, pwr_oe3, pwr_oe4; input [7:0] adc_d; output adc_clk; input ssp_dout; output ssp_frame, ssp_din, ssp_clk; output dbg; input [3:0] mod_type; assign adc_clk = ck_1356meg; // The comparator with hysteresis on the output from the peak detector. reg after_hysteresis; reg [11:0] has_been_low_for; always @(negedge adc_clk) begin if (& adc_d[7:5]) after_hysteresis <= 1'b1; // if (adc_d >= 224) else if (~(| adc_d[7:5])) after_hysteresis <= 1'b0; // if (adc_d <= 31) if (adc_d >= 224) begin has_been_low_for <= 12'd0; end else begin if (has_been_low_for == 12'd4095) begin has_been_low_for <= 12'd0; after_hysteresis <= 1'b1; end else begin has_been_low_for <= has_been_low_for + 1; end end end // Divide 13.56 MHz to produce various frequencies for SSP_CLK // and modulation. reg [8:0] ssp_clk_divider; always @(negedge adc_clk) ssp_clk_divider <= (ssp_clk_divider + 1); reg ssp_clk; always @(negedge adc_clk) begin if (mod_type == `FPGA_HF_SIMULATOR_MODULATE_424K_8BIT) // Get bit every at 53KHz (every 8th carrier bit of 424kHz) ssp_clk <= ~ssp_clk_divider[7]; else if (mod_type == `FPGA_HF_SIMULATOR_MODULATE_212K) // Get next bit at 212kHz ssp_clk <= ~ssp_clk_divider[5]; else // Get next bit at 424Khz ssp_clk <= ~ssp_clk_divider[4]; end // Produce the byte framing signal; the phase of this signal // is arbitrary, because it's just a bit stream in this module. reg ssp_frame; always @(negedge adc_clk) begin if (mod_type == `FPGA_HF_SIMULATOR_MODULATE_212K) begin if (ssp_clk_divider[8:5] == 4'd1) ssp_frame <= 1'b1; if (ssp_clk_divider[8:5] == 4'd5) ssp_frame <= 1'b0; end else begin if (ssp_clk_divider[7:4] == 4'd1) ssp_frame <= 1'b1; if (ssp_clk_divider[7:4] == 4'd5) ssp_frame <= 1'b0; end end // Synchronize up the after-hysteresis signal, to produce DIN. reg ssp_din; always @(posedge ssp_clk) ssp_din = after_hysteresis; // Modulating carrier frequency is fc/64 (212kHz) to fc/16 (848kHz). Reuse ssp_clk divider for that. reg modulating_carrier; always @(*) if (mod_type == `FPGA_HF_SIMULATOR_NO_MODULATION) modulating_carrier <= 1'b0; // no modulation else if (mod_type == `FPGA_HF_SIMULATOR_MODULATE_BPSK) modulating_carrier <= ssp_dout ^ ssp_clk_divider[3]; // XOR means BPSK else if (mod_type == `FPGA_HF_SIMULATOR_MODULATE_212K) modulating_carrier <= ssp_dout & ssp_clk_divider[5]; // switch 212kHz subcarrier on/off else if (mod_type == `FPGA_HF_SIMULATOR_MODULATE_424K || mod_type == `FPGA_HF_SIMULATOR_MODULATE_424K_8BIT) modulating_carrier <= ssp_dout & ssp_clk_divider[4]; // switch 424kHz modulation on/off else modulating_carrier <= 1'b0; // yet unused // Load modulation. Toggle only one of these, since we are already producing much deeper // modulation than a real tag would. assign pwr_hi = 1'b0; // HF antenna connected to GND assign pwr_oe3 = 1'b0; // 10k Load assign pwr_oe1 = 1'b0; // 33 Ohms Load assign pwr_oe4 = modulating_carrier; // 33 Ohms Load // This is all LF and doesn't matter assign pwr_lo = 1'b0; assign pwr_oe2 = 1'b0; assign dbg = ssp_frame; endmodule
//----------------------------------------------------- // Design Name : hw2_A_testbench // File Name : hw2_A_testbench.v // Function : This program will test hw2_A.v // Coder : hydai //----------------------------------------------------- `timescale 1 ns/1 ns module hw2_A_testbench ; reg in; reg clk, rst_n; wire out; hw2_A A( in, clk, rst_n, out, ); initial begin #0 rst_n = 1'b0; clk = 1'b0; #20 rst_n = 1'b1; in = 1'b0; $display ("===================================================================="); $display ("Time %t", $time); $display ("rst_n = %b\tin = %b\tout = %b", rst_n, in, out); $display ("===================================================================="); end wire [20:0] inputArr = 21'b0101_0011_1110_0010_1110_0; // Test pattern integer i; initial begin #20 $display ("Simulate hw2_A"); for (i = 20; i >= 0; i = i - 1) begin #20 in = inputArr[i]; $display ("===================================================================="); $display ("Time %t", $time); $display ("rst_n = %b\tin = %b\tout = %b", rst_n, in, out); $display ("===================================================================="); end #40 $finish; end always begin #10 clk = ~clk; end initial begin $fsdbDumpfile("hw2_A_testbench.fsdb"); $fsdbDumpvars; end endmodule // End of Module hw2_A_testbench
/* -- ============================================================================ -- FILE : bus_arbiter.v -- SYNOPSIS : ×ÜÏßÖÙ²ÃÆ÷Ä£¿é£¬Ê¹ÓÃÂÖѯ»úÖÆ°´ÇëÇó˳Ðò½øÐÐʹÓÃȨ·ÖÅ䣬ÇÒÆ½µÈ¶Ô´ýËùÓÐ×ÜÏßÖ÷¿Ø -- ---------------------------------------------------------------------------- -- Revision Date Coding_by Comment -- 1.0.0 2011/06/27 suito ÐÂҎ×÷³É -- ============================================================================ */ /********** ͨÓÃÍ·Îļþ **********/ `include "nettype.h" `include "stddef.h" `include "global_config.h" /********** Ä£¿éÍ·Îļþ **********/ `include "bus.h" /********** ×ÜÏßÖÙ²ÃÆ÷ **********/ module bus_arbiter ( /********** ʱÖÓÓ븴λ **********/ input wire clk, // ʱÖÓ input wire reset, // Òì²½¸´Î» /********** ÊäÈëÊä³öÐźŠ**********/ // 0ºÅ×ÜÏßÖ÷¿Ø input wire m0_req_, // ÇëÇó×ÜÏß output reg m0_grnt_, // ¸³Óè×ÜÏß // 1ºÅ×ÜÏßÖ÷¿Ø input wire m1_req_, // ÇëÇó×ÜÏß output reg m1_grnt_, // ¸³Óè×ÜÏß // 2ºÅ×ÜÏßÖ÷¿Ø input wire m2_req_, // ÇëÇó×ÜÏß output reg m2_grnt_, // ¸³Óè×ÜÏß // 3ºÅ×ÜÏßÖ÷¿Ø input wire m3_req_, // ÇëÇó×ÜÏß output reg m3_grnt_ // ¸³Óè×ÜÏß ); /********** ÄÚ²¿ÐźŠ**********/ reg [`BusOwnerBus] owner; // ×ÜÏßµ±Ç°ËùÓÐÕß /********** ¸³Óè×ÜÏßʹÓÃȨ**********/ always @(*) begin /* ¸³Óè×ÜÏßʹÓÃȨ³õʼ»¯ */ m0_grnt_ = `DISABLE_; m1_grnt_ = `DISABLE_; m2_grnt_ = `DISABLE_; m3_grnt_ = `DISABLE_; /* ¸³Óè×ÜÏßʹÓÃȨ */ case (owner) `BUS_OWNER_MASTER_0 : begin // 0ºÅ×ÜÏßÖ÷¿Ø m0_grnt_ = `ENABLE_; end `BUS_OWNER_MASTER_1 : begin // 1ºÅ×ÜÏßÖ÷¿Ø m1_grnt_ = `ENABLE_; end `BUS_OWNER_MASTER_2 : begin // 2ºÅ×ÜÏßÖ÷¿Ø m2_grnt_ = `ENABLE_; end `BUS_OWNER_MASTER_3 : begin // 3ºÅ×ÜÏßÖ÷¿Ø m3_grnt_ = `ENABLE_; end endcase end /********** ×ÜÏßʹÓÃȨÖٲà **********/ always @(posedge clk or `RESET_EDGE reset) begin if (reset == `RESET_ENABLE) begin /* Òì²½¸´Î» */ owner <= #1 `BUS_OWNER_MASTER_0; end else begin /* Öٲà */ case (owner) `BUS_OWNER_MASTER_0 : begin // ×ÜÏßʹÓÃȨËùÓÐÕߣº0ºÅ×ÜÏßÖ÷¿Ø /* ÏÂÒ»¸ö»ñµÃ×ÜÏßʹÓÃȨµÄÖ÷¿Ø */ if (m0_req_ == `ENABLE_) begin // 0ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_0; end else if (m1_req_ == `ENABLE_) begin // 1ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_1; end else if (m2_req_ == `ENABLE_) begin // 2ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_2; end else if (m3_req_ == `ENABLE_) begin // 3ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_3; end end `BUS_OWNER_MASTER_1 : begin // ×ÜÏßʹÓÃȨËùÓÐÕߣº1ºÅ×ÜÏßÖ÷¿Ø /* ÏÂÒ»¸ö»ñµÃ×ÜÏßʹÓÃȨµÄÖ÷¿Ø */ if (m1_req_ == `ENABLE_) begin // 1ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_1; end else if (m2_req_ == `ENABLE_) begin // 2ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_2; end else if (m3_req_ == `ENABLE_) begin // 3ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_3; end else if (m0_req_ == `ENABLE_) begin // 0ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_0; end end `BUS_OWNER_MASTER_2 : begin // ×ÜÏßʹÓÃȨËùÓÐÕߣº2ºÅ×ÜÏßÖ÷¿Ø /* ÏÂÒ»¸ö»ñµÃ×ÜÏßʹÓÃȨµÄÖ÷¿Ø */ if (m2_req_ == `ENABLE_) begin // 2ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_2; end else if (m3_req_ == `ENABLE_) begin // 3ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_3; end else if (m0_req_ == `ENABLE_) begin // 0ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_0; end else if (m1_req_ == `ENABLE_) begin // 1ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_1; end end `BUS_OWNER_MASTER_3 : begin // ×ÜÏßʹÓÃȨËùÓÐÕߣº3ºÅ×ÜÏßÖ÷¿Ø /* ÏÂÒ»¸ö»ñµÃ×ÜÏßʹÓÃȨµÄÖ÷¿Ø */ if (m3_req_ == `ENABLE_) begin // 3ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_3; end else if (m0_req_ == `ENABLE_) begin // 0ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_0; end else if (m1_req_ == `ENABLE_) begin // 1ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_1; end else if (m2_req_ == `ENABLE_) begin // 2ºÅ×ÜÏßÖ÷¿Ø owner <= #1 `BUS_OWNER_MASTER_2; end end endcase end end endmodule
#include <bits/stdc++.h> using namespace std; const int MaxN = 100009; unsigned long long a[MaxN], b[MaxN], c[MaxN]; int main() { unsigned long long n, ans = 0, p, sum = 0, sum2 = 0; cin >> n >> p; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) { sum += a[i]; b[i] = sum % p; } for (int i = n - 1; i >= 0; i--) { sum2 += a[i]; c[i] = sum2 % p; } for (int i = 0; i < n; i++) ans = max(ans, (b[i] + c[i + 1])); cout << ans << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int piles = 1, heavy = 0, num; int a[110], n; void solve(int x) { if (num == 0) { return; } if (heavy <= a[x]) { a[x] = -1; heavy++; num--; solve(x + 1); } else if (x < n) { solve(x + 1); } else { for (int i = 1; i <= n; i++) { if (a[i] != -1) { a[i] = -1; num--; heavy = 1; piles++; break; } } solve(1); } } int main() { cin >> n; num = n; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { if (a[i] < a[j]) { swap(a[i], a[j]); } } } solve(1); cout << piles; return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int a[n], ans = 0, maxi = 0; for (int i = 0; i < 7; i++) { cin >> a[i]; maxi += a[i]; } int t; if (maxi >= n) t = 1; else if (n % maxi == 0) { t = n / maxi; } else { t = n / maxi + 1; } while (t--) { for (int i = 0; i < 7; i++) { n -= a[i]; if (n <= 0) { ans = i + 1; break; } } } cout << ans << n ; return 0; }
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_LP__UDP_DFF_PS_PP_PKG_SN_BLACKBOX_V `define SKY130_FD_SC_LP__UDP_DFF_PS_PP_PKG_SN_BLACKBOX_V /** * udp_dff$PS_pp$PKG$sN: Positive edge triggered D flip-flop with * active high * * Verilog stub definition (black box with power pins). * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none (* blackbox *) module sky130_fd_sc_lp__udp_dff$PS_pp$PKG$sN ( Q , D , CLK , SET , SLEEP_B , NOTIFIER, KAPWR , VGND , VPWR ); output Q ; input D ; input CLK ; input SET ; input SLEEP_B ; input NOTIFIER; input KAPWR ; input VGND ; input VPWR ; endmodule `default_nettype wire `endif // SKY130_FD_SC_LP__UDP_DFF_PS_PP_PKG_SN_BLACKBOX_V
#include <bits/stdc++.h> using namespace std; long long a[100005]; void solve() { long long n; cin >> n; for (long long i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); vector<long long> ans; long long st = 0, end = n - 1; while (end > st) { ans.push_back(a[end]); ans.push_back(a[st]); st++; end--; } if (st == end) { ans.push_back(a[st]); } reverse((ans).begin(), (ans).end()); for (auto i : ans) { cout << i << ; } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long t = 1; cin >> t; while (t--) { solve(); cout << n ; } return 0; }
#include <bits/stdc++.h> using namespace std; long long int n, k, ans; long long int check(long long int v) { long long int sum = 0; while (v > 0) { sum += v; v /= k; } return sum; } void BS(long long int l, long long int r) { while (l <= r) { long long int mid = (l + (r - l) / 2); long long int sum = check(mid); if (sum >= n) { r = mid - 1; ans = min(ans, mid); } else l = mid + 1; } } void solve() { cin >> n >> k; ans = n; long long int l, r; l = 1; r = n; BS(l, r); cout << ans << n ; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); return 0; }
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HS__NOR4BB_2_V `define SKY130_FD_SC_HS__NOR4BB_2_V /** * nor4bb: 4-input NOR, first two inputs inverted. * * Verilog wrapper for nor4bb with size of 2 units. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none `include "sky130_fd_sc_hs__nor4bb.v" `ifdef USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_hs__nor4bb_2 ( Y , A , B , C_N , D_N , VPWR, VGND ); output Y ; input A ; input B ; input C_N ; input D_N ; input VPWR; input VGND; sky130_fd_sc_hs__nor4bb base ( .Y(Y), .A(A), .B(B), .C_N(C_N), .D_N(D_N), .VPWR(VPWR), .VGND(VGND) ); endmodule `endcelldefine /*********************************************************/ `else // If not USE_POWER_PINS /*********************************************************/ `celldefine module sky130_fd_sc_hs__nor4bb_2 ( Y , A , B , C_N, D_N ); output Y ; input A ; input B ; input C_N; input D_N; // Voltage supply signals supply1 VPWR; supply0 VGND; sky130_fd_sc_hs__nor4bb base ( .Y(Y), .A(A), .B(B), .C_N(C_N), .D_N(D_N) ); endmodule `endcelldefine /*********************************************************/ `endif // USE_POWER_PINS `default_nettype wire `endif // SKY130_FD_SC_HS__NOR4BB_2_V
#include <bits/stdc++.h> using namespace std; template <class T> inline T bigmod(T p, T e, T M) { long long ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); } template <class T> inline T modinverse(T a, T M) { return bigmod(a, M - 2, M); } template <class T> inline T lcm(T a, T b) { a = abs(a); b = abs(b); return (a / gcd(a, b)) * b; } template <class T, class X> inline bool getbit(T a, X i) { T t = 1; return ((a & (t << i)) > 0); } template <class T, class X> inline T setbit(T a, X i) { T t = 1; return (a | (t << i)); } template <class T, class X> inline T resetbit(T a, X i) { T t = 1; return (a & (~(t << i))); } inline long long getnum() { char c = getchar(); long long num, sign = 1; for (; c < 0 || c > 9 ; c = getchar()) if (c == - ) sign = -1; for (num = 0; c >= 0 && c <= 9 ;) { c -= 0 ; num = num * 10 + c; c = getchar(); } return num * sign; } inline long long power(long long a, long long b) { long long multiply = 1; for (int i = (0); i < (b); i++) { multiply *= a; } return multiply; } int n, q, type, l, r, k, a[100002], blockSZ; vector<int> v[318]; int sz, cnt[100002][318]; void Shift(int to, int from) { int b1 = -1, b2 = -1; int s = 0, idx1, idx2; if (to == from) return; for (int i = (0); i < (sz + 1); i++) { if (b1 == -1 && s + (int)v[i].size() > from) { b1 = from - s; idx1 = i; } if (b2 == -1 && s + (int)v[i].size() > to) { b2 = to - s; idx2 = i; } s += v[i].size(); } int val = v[idx1][b1]; v[idx1].erase(v[idx1].begin() + b1); v[idx2].insert(v[idx2].begin() + b2, val); cnt[val][idx1]--; cnt[val][idx2]++; } int Query(int from, int to, int x) { int s = 0, idx1 = -1, idx2 = -1, b1 = -1, b2 = -1; for (int i = (0); i < (sz + 1); i++) { if (idx1 == -1 && s + (int)v[i].size() > from) { idx1 = i; b1 = from - s; } if (idx2 == -1 && s + (int)v[i].size() > to) { idx2 = i; b2 = to - s; } s += v[i].size(); } int ret = 0; for (int i = (idx1 + 1); i < (idx2); i++) { ret += cnt[x][i]; } if (idx1 != idx2) { for (int i = (b1); i < (v[idx1].size()); i++) { if (v[idx1][i] == x) ret++; } for (int i = (0); i < (b2 + 1); i++) { if (v[idx2][i] == x) ret++; } } else { for (int i = (b1); i < (b2 + 1); i++) { if (v[idx1][i] == x) ret++; } } return ret; } void Rebuild() { vector<int> temp; for (int i = (0); i < (sz + 1); i++) { for (int j = (0); j < (v[i].size()); j++) { temp.push_back(v[i][j]); cnt[v[i][j]][i]--; } v[i].clear(); } sz = 0; for (int i = (0); i < (n); i++) { v[sz].push_back(temp[i]); cnt[temp[i]][sz]++; if (i + 1 < n && (i + 1) % blockSZ == 0) sz++; } } void Print() { cout << All numbers: ; for (int i = (0); i < (sz + 1); i++) { for (int j = (0); j < (v[i].size()); j++) cout << v[i][j] << ; } cout << n ; cout << All vectors: << n ; for (int i = (0); i < (sz + 1); i++) { for (int J = (0); J < (v[i].size()); J++) cout << v[i][J] << ; cout << n ; } } int main() { int test, cases = 1; scanf( %d , &n); blockSZ = 700; for (int i = (0); i < (n); i++) { scanf( %d , &a[i]); } for (int i = (0); i < (n); i++) { v[sz].push_back(a[i]); cnt[a[i]][sz]++; if (i + 1 < n && (i + 1) % blockSZ == 0) sz++; } scanf( %d , &q); int last = 0, shift = 0; while (q--) { scanf( %d , &type); if (type == 1) { scanf( %d%d , &l, &r); l = ((l + last - 1) % n) + 1; r = ((r + last - 1) % n) + 1; l--, r--; if (l > r) swap(l, r); Shift(l, r); shift++; } else { scanf( %d%d%d , &l, &r, &k); l = ((l + last - 1) % n) + 1; r = ((r + last - 1) % n) + 1; k = ((k + last - 1) % n) + 1; l--, r--; if (l > r) swap(l, r); last = Query(l, r, k); printf( %d n , last); } if (shift == 1200) { Rebuild(); shift = 0; } } return 0; }
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HD__SDLCLKP_PP_SYMBOL_V `define SKY130_FD_SC_HD__SDLCLKP_PP_SYMBOL_V /** * sdlclkp: Scan gated clock. * * Verilog stub (with power pins) for graphical symbol definition * generation. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none (* blackbox *) module sky130_fd_sc_hd__sdlclkp ( //# {{scanchain|Scan Chain}} input SCE , //# {{clocks|Clocking}} input CLK , input GATE, output GCLK, //# {{power|Power}} input VPB , input VPWR, input VGND, input VNB ); endmodule `default_nettype wire `endif // SKY130_FD_SC_HD__SDLCLKP_PP_SYMBOL_V
/** * Copyright 2020 The SkyWater PDK Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ `ifndef SKY130_FD_SC_HD__DLRBN_PP_SYMBOL_V `define SKY130_FD_SC_HD__DLRBN_PP_SYMBOL_V /** * dlrbn: Delay latch, inverted reset, inverted enable, * complementary outputs. * * Verilog stub (with power pins) for graphical symbol definition * generation. * * WARNING: This file is autogenerated, do not modify directly! */ `timescale 1ns / 1ps `default_nettype none (* blackbox *) module sky130_fd_sc_hd__dlrbn ( //# {{data|Data Signals}} input D , output Q , output Q_N , //# {{control|Control Signals}} input RESET_B, //# {{clocks|Clocking}} input GATE_N , //# {{power|Power}} input VPB , input VPWR , input VGND , input VNB ); endmodule `default_nettype wire `endif // SKY130_FD_SC_HD__DLRBN_PP_SYMBOL_V
`timescale 1ns / 1ps module MoleDecoder(mole16bit, mole_position); input [4:0]mole_position; output [15:0]mole16bit; reg [15:0]mole16bit; always @( * )begin case(mole_position) 5'd0: mole16bit = 16'b0000_0000_0000_0001; 5'd1: mole16bit = 16'b0000_0000_0000_0010; 5'd2: mole16bit = 16'b0000_0000_0000_0100; 5'd3: mole16bit = 16'b0000_0000_0000_1000; 5'd4: mole16bit = 16'b0000_0000_0001_0000; 5'd5: mole16bit = 16'b0000_0000_0010_0000; 5'd6: mole16bit = 16'b0000_0000_0100_0000; 5'd7: mole16bit = 16'b0000_0000_1000_0000; 5'd8: mole16bit = 16'b0000_0001_0000_0000; 5'd9: mole16bit = 16'b0000_0010_0000_0000; 5'd10:mole16bit = 16'b0000_0100_0000_0000; 5'd11:mole16bit = 16'b0000_1000_0000_0000; 5'd12:mole16bit = 16'b0001_0000_0000_0000; 5'd13:mole16bit = 16'b0010_0000_0000_0000; 5'd14:mole16bit = 16'b0100_0000_0000_0000; 5'd15:mole16bit = 16'b1000_0000_0000_0000; default: mole16bit = 16'b0000_0000_0000_0000; endcase end endmodule