PHP Program to Generate Permutation by Swaps with Explanation
PHP
Hard
PHP Functions
30 views
1 min read
110 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around swap, line, generate. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Given n and a list of swaps (i j), start with [1..n]. Apply swaps and print the final array.
Input Format
First line n q. Next q lines i j (1-based).
Output Format
One line n integers.
Constraints
n,q
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$first=preg_split('/\\s+/', trim($inputLines[0] ?? ''));
$n=intval($first[0] ?? 0);
$q=intval($first[1] ?? 0);
$a=[];
for($i=1;$i<=$n;$i++) $a[]=$i;
for($k=0;$k<$q;$k++){
$tokens=preg_split('/\\s+/', trim($inputLines[$k+1] ?? ''));
$i=intval($tokens[0] ?? 1)-1;
$j=intval($tokens[1] ?? 1)-1;
$tmp=$a[$i]; $a[$i]=$a[$j]; $a[$j]=$tmp;
}
echo implode(' ',array_map('strval',$a));
?>
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Given n and a list of swaps (i j), start with [1..n]. Apply swaps and print the final array.
Input / Output
Input
First line n q. Next q lines i j (1-based).
Output
One line n integers.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$first=preg_split('/\\s+/', trim($inputLines[0] ?? ''));
$n=intval($first[0] ?? 0);
$q=intval($first[1] ?? 0);
$a=[];
for($i=1;$i<=$n;$i++) $a[]=$i;
for($k=0;$k<$q;$k++){
$tokens=preg_split('/\\s+/', trim($inputLines[$k+1] ?? ''));
$i=intval($tokens[0] ?? 1)-1;
$j=intval($tokens[1] ?? 1)-1;
$tmp=$a[$i]; $a[$i]=$a[$j]; $a[$j]=$tmp;
}
echo implode(' ',array_map('strval',$a));
?>
Solutions (0)
No solutions submitted yet. Be the first!