了解freopen函数

Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let’s index all cards by consecutive integers from 1 to 2n. We’ll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.


Input
The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, …, a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces.
Output
If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs.
Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.


Examples
Input--------------------------(1)
3
20 30 10 30 20 10
Output
4 2
1 5
6 3
Input--------------------------(2)
1
1 2
Output
-1
**
C 代码

#include<stdio.h>
#include<algorithm>
using namespace std;
struct M
{
 int a;
 int b;
}p[1000000];
bool l1(M x,M y)
{
 return x.a<y.a;
}
int main()
{
 freopen("input.text","r",stdin);
 freopen("output.text","w",stdout);
 int m,i,f=0;
 scanf("%d",&m);
 for(i=1;i<=2*m;i++)
 {
  scanf("%d",&p[i].a);
  p[i].b=i;
 }
 sort(p+1,p+2*m+1,l1);
 for(i=1;i<=2*m;i+=2)
 {
  if(p[i].a!=p[i+1].a)
  {
   f=1;
   break;
  } 
 }
 if(f)
 printf("-1\n");
 else 
 for(i=1;i<=2*m;i+=2)
 printf("%d %d\n",p[i].b,p[i+1].b);
 return 0;
}

不知道为什无法运行,但是知道了freopen函数
freopen函数可以解决测试数据输入问题,避免重复输入,是一种简单而有效的解决方法。
功能:实现重定向,把预定义的标准流文件定向到有path指定的文件中。标准流文件具体指stdin、stdout和stderr,其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认,通过调用freopen就可以修改标准流文件的默认值,实现重定向。

#include <stdio.h> 
#include <iostream> 
using namespace std; 
int main() 
{     
	int a,b;     
	freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取    
	freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在	out.txt文件中    
	while(cin>> a >> b)         
		cout<< a+b <<endl; // 注意使用endl    
	fclose(stdin);//关闭文件    
	fclose(stdout);//关闭文件    
	return 0; 
}
freopen("in.txt","r",stdin)的作用就是把标准输入流stdin重定向到in.txt文件中,这样在用scanf或是用cin输入时便不会从标准输入流读取数据,而是从in.txt文件中获取输入。只要把输入数据事先粘贴到in.txt,调试时就方便多了。 类似的,freopen("out.txt","w",stdout)的作用就是把stdout重定向到out.txt文件中,这样输出结果需要打开out.txt文件查看。
ZL0
发布了15 篇原创文章 · 获赞 0 · 访问量 223

猜你喜欢

转载自blog.csdn.net/ZL0_bo/article/details/104269174
今日推荐